Friday, 16 September 2016

inheritance - C++ assignment operator implementation on derived class





Suppose I have a base class which looks like this:



class Base
{
public:
Base(){ baseMember = new int( 10 ); }

Base &operator=( const Base &right )
{
baseMember = new int( *(right.baseMember) );

return *this;
}
protected:
int *baseMember;
};


And now I want to have a Derived class which inherits from Base, and have a new pointer member called derivedMember:



class Derived : public Base

{
public:
Derived():Base(){ derivedMember = new double( 10.1 ); }

Derived &operator=( const Derived &right )
{ /*some implementation */ }
private:
double *derivedMember;
};



How should I do the operator= implementation on the Derived class in a way which I can call the base class operator= and avoid having to rewrite the Base class operator= implementation on the Derived class? In simple words, how can I avoid having to do it:



Derived &operator=(const Derived &right )
{
baseMember = new int( *(right.baseMember) ); //this is what I want to avoid rewriting
derivedMember = new double( *(right.derivedMember) );
return *this;
}


Answer



Like this:



Derived &operator=(const Derived &right )
{
if (&right == this) { return *this; } // prevent assigning to self
Base::operator=(right);
delete derivedMember; // remember to release any assigned memory (assumes derivedMember is assigned a default of nullPtr)
derivedMember = new double( *(right.derivedMember) );
return *this;

}

No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...