1

Say I have this C++ code:

class Base {
public:
 Base& operator=(const Base&);
};

class Derivate : public Base {
public:

};

And say I have a main where

Derivate d1;
//Something on d1
Derivate d2 = d1;

In this situation would the operator = of the base class called? I have some code that basically does such thing, but debugging with gdb I don't see any call to such operator.

Is it necessary in this case redifine the operator in the derivate class?

user8469759
  • 2,522
  • 6
  • 26
  • 50

1 Answers1

0

no in fact you are calling copy constructor because you are assigning d1 to d2 while constructing d2 thus assignment operator is not called here:

#include <iostream>
using namespace std;

class Base 
{
    public:
        Base& operator = (const Base&);
};

Base& Base::operator = (const Base&)
{
    cout << "assignment operator" << endl;
    // implementation here
    return *this;
}

class Derivate : public Base
{
    public:
        Derivate(){}
        Derivate(const Derivate& rhs){cout << "copy constructor" << endl;}
};

int main()
{
    Derivate d1;
    //Something on d1
    Derivate d2 = d1; // copy constructor not assignment operstor
    //Derivate d2(d1); // is the same as above calling cpy ctor
    d2 = d1; // here assignment operator is called

    return 0;
}
  • why d2 = d1; calls the base assignment operator?

because if you don't provide a derived class assignment operator the compiler will define one for you as follows:

Derivate& operator = (const Base& rhs); // not Derivate

so this Derived one calls as you guess the base's assignment operator as long as passing a const reference instead of derived one.

  • assignment operator is really inherited:

make it private scoped in base class and see the result.

Raindrop7
  • 3,889
  • 3
  • 16
  • 27
  • The automatically declared assignment operator is `Derivate& operator=(const Derivate&);`, not `Derivate& operator=(const Base&);`. – aschepler Nov 14 '16 at 20:45
  • @aschepler yes I know I said the compiler adds implicitly `Derivate& operator=(const Base&);` which in turn invokes the base one – Raindrop7 Nov 14 '16 at 20:46