Sick of initializing and assigning values to the base class's data members? Absolve yourself of this responsibility by overloading the copy constructor and the assignment operator in the derived class.
As soon as the compiler discovers you've done this, it stops the implicit invocation of the base class's default copy constructor and assignment operator. In the following example, the compiler checks to see if the derived class has an overloaded assignment operator. When it finds that it does not, it prepares the default assignment and goes to the base class and find that it has not overloaded the assignment operator either. It next invokes the base class default assignment operator, then invokes the derived class's default assignment operator.
class derived: public base
The same holds true for this second example, where the default copy constructor of both classes is invoked:
derived d, d1;
d = d1;
Remember, if you overload any of these in the derived class, the compiler will not even check the base classleaving you to handle the initialization or assignment for the base class.
In the case of the copy constructor, you can make an explicit call to the base class' default copy constructor in the member intialization list:
derived(const derived& d) : base(d)
In the case of the assignment operator, however, you need to use a work-around:
derived& operator = (const derived& d)
if (&d != this)
static_cast<base&>((*this)) = c;
//base::operator = (c);
You can do this two ways:
- If you use the following method, do not forget to cast by reference, lest you end up assigning to some other base objectand not the sub-object of the derived:
static_cast((*this)) = c;
- Make a direct call to the base::operator.
2- base::operator = (c);