Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

overloading assignment operators when the class is a child

How do you set base class members using the assignment operator implementation? If for example someone defines the assignment operator in a derived class like this:

(where both colour and Colour() are members of the base class - meaning the lines indicated below are illegal)

Derived& Derived::operator=(const Derived& rhs) 
{
if (&rhs != this)
{

    Colour(rhs.colour);    // not allowed
        Colour(rhs.Colour());  // not allowed
}
return *this;
}

what is the solution? Is there a way of linking operator overloads in the base? Do I do something like...

Derived& Derived::operator=(const Derived& rhs) : Base::operator=(rhs)
...?
like image 749
Dollarslice Avatar asked Dec 08 '11 16:12

Dollarslice


1 Answers

It is done like this :

class B
{
 public:
  B& operator=( const B & other )
  {
    v = other.v;
    return *this;
  }
  int v;
};

class D : public B
{
 public:
  D& operator=( const D & other )
  {
    B::operator=( other );
    return *this;
  }
};
like image 144
BЈовић Avatar answered Nov 23 '22 17:11

BЈовић