Stop Initializing and Assigning Values to the Base Class’s Data Members

Stop Initializing and Assigning Values to the Base Class’s Data Members

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 base{};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;derived d2(d1);

Remember, if you overload any of these in the derived class, the compiler will not even check the base class?leaving 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((*this)) = c;		//or		//base::operator = (c);	}}

You can do this two ways:

  1. If you use the following method, do not forget to cast by reference, lest you end up assigning to some other base object?and not the sub-object of the derived:
    static_cast((*this)) = c;
  2. Make a direct call to the base::operator.
    2- base::operator = (c);


Share the Post: