kberson
kberson

Reputation: 438

deriving from a template

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

Upvotes: 3

Views: 316

Answers (2)

Robᵩ
Robᵩ

Reputation: 168626

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.)

Upvotes: 3

Boaz Yaniv
Boaz Yaniv

Reputation: 6424

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.

Upvotes: 1

Related Questions