0

In the best rated answer to the question from this link, I don't understand how the derived assignment operator calls the assignment operator from the base class, i.e., this in this part of the code:

Derived& operator=(const Derived& d)
{
    Base::operator=(d);
    additional_ = d.additional_;
    return *this;
}

what does

Base::operator=(d)

mean? What does it do? Cheers!

Community
  • 1
  • 1
Simon Righley
  • 4,538
  • 6
  • 26
  • 33

2 Answers2

4

Base::operator= calls the Base class version of operator= to copy the parts of the object that are part of Base and then the derived class copies the rest. Since the base class already does all the work required correctly why repeat the work, just reuse. So let's take this simplified example:

class Base
{
   std::string
      s1 ;
   int
      i1 ;
   public:
     Base& operator =( const Base& b)  // method #1
     {
        // trvial probably not good practice example
        s1 = b.s1 ;
        i1 = b.i1 ;

        return *this ;
     }
} ;

class Derived : Base
{
   double
     d1 ;
   public:
     Derived& operator =(const Derived& d ) // method #2
     {
       // trvial probably not good practice example
       Base::operator=(d) ;
       d1 = d.d1 ;
       return *this ;

     }

} ;

Derived will have three member variables, two from Base: s1 and i1 and one of it's own d1. So Base::operator= calls what I have labeled as method #1 which copies the two variables that Derived inherited from Base which are s1 and i1 and so that all that is left to copy is d1 which is what method #2 takes care of.

Shafik Yaghmour
  • 154,301
  • 39
  • 440
  • 740
1

It's just a call to a member function on the current object. The current object inherited a function whose fully-qualified name is Base::operator=, and you can call it just like any other non-static member function.

Ben Voigt
  • 277,958
  • 43
  • 419
  • 720
  • Ben: Oh, so I need to think that "Base::operator=(d)" is called ON the derived object (as any other member function would be)! I thought along the lines that "entire functions" act on objects, I hadn't thought about smth in an actual body of the function doing that. True, true. So, this takes care for the base part of the assignment operation, and then I need of course to assign any extra data data Derived has. Got it, thanks a lot. – Simon Righley Mar 14 '13 at 20:21