I have code like this:
class Base
{
public:
void operator = (const Base& base_)
{
}
};
class Child : public Base
{
public:
};
void func()
{
const Base base;
Child child;
child = base;
}
My question is: since Child derives from Base (hence it should inherit Base's operator= ), how come when the statement
child = base;
is executed, I get a compiler error like this:
>.\main.cpp(78) : error C2679: binary '=' : no operator found which takes a right-hand operand of type 'const Base' (or there is no acceptable conversion)
1> .\main.cpp(69): could be 'Child &Child::operator =(const Child &)'
1> while trying to match the argument list '(Child, const Base)'
The behavior that I want is for the Child class to recognize that it's being assigned a Base class, and just "automatically" call the its parent's operator=.
Once I added this code to the Child class
void operator = (const Base& base_)
{
Base::operator=(base_);
}
then everything compiled fine. Though I dont think this would be good because if I have like 5 different classes that inherit from Base, then I have to repeat the same code in every single derived class.
NOTE: My intention for copying the Base
to Child
is to simply copying the members that are common to both Base
and Child
(which would be all the members of Base
). Even after reading all of the answers below, I really don't see why C++ doesn't allow one to do this, especially if there's an explicit operator=
defined in the Base
class.