3

I'm stuck on the following and could use some help:

typedef unsigned short USHORT;

template <typename DataType>
class Primative
{
protected:
    DataType m_dtValue;
public:
    Primative() : m_dtValue(0) {}

    DataType operator=(const DataType c_dtValue) { return m_dtValue = c_dtValue; }
    DataType Set(const DataType c_dtValue){ return m_dtValue = c_dtValue; }
};

typedef Primative<USHORT> PrimativeUS;

class Evolved : public PrimativeUS
{
public:
    Evolved() {}
};

int main()
{
    PrimativeUS prim;
    prim = 4;

    Evolved evo;
    evo.Set(5);  // good
    evo = USHORT(5); // error, no operator found which takes a right-hand operator...
}

It looks like the derived class is not getting the overloaded operator

kberson
  • 439
  • 1
  • 3
  • 8
  • I forgot to include that calling **evo.Set(5)** works – kberson May 12 '11 at 16:11
  • You've asked questions but not accepted answer for even one. Disappointing! – Nawaz May 12 '11 at 16:19
  • please indicate your acceptance of the answers to your previous questions. Please upvote any answer that helped you, and accept the answer that you find most helpful. More information and instructions are [here](http://stackoverflow.com/faq#howtoask). – Robᵩ May 12 '11 at 16:29
  • +1 for including a Short, Self-contained, Complete Example. (see http://sscce.org). – Robᵩ May 12 '11 at 16:36

2 Answers2

3

Try this:

class Evolved : public PrimativeUS
{
public:
  using PrimativeUS::operator=;
  Evolved() {}
};

The implicit Evolved::operator=(const Evovled&) that is provided for you hides all instances of operator= present in the base class. (This is true of any method - methods of derived classes hide similarly-named methods of base class, even if the signatures don't match.)

Robᵩ
  • 163,533
  • 20
  • 239
  • 308
  • +1 I didn't know the implicit `operator=` hid explicit parent assignment operators. – Mark B May 12 '11 at 16:42
  • Thanks; I also did not know that implicit `operator=` was hidden, and this solution works. – kberson May 12 '11 at 17:07
  • @kberson, I'm glad this solution works for you. Would you please upvote and accept the answers to this and your previous questions? – Robᵩ May 12 '11 at 17:11
1

Change your function declaration slightly:

DataType operator=(const DataType& c_dtValue) { return m_dtValue = c_dtValue; }
DataType Set(const DataType& c_dtValue){ return m_dtValue = c_dtValue; }

Note that a & (reference) sign is needed for operator overloading.

Boaz Yaniv
  • 6,334
  • 21
  • 30