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.