Flowing from the pattern

I am stuck with the following and can 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 an overloaded operator

+3
source share
2 answers

Try the following:

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

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

+3
source

Change the function declaration a bit:

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

Note that to overload the operator, the a and (reference) signs are required.

+1
source

All Articles