Assignment operator inheritance
There is this code:
#include <iostream>
class Base {
public:
Base(){
std::cout << "Constructor base" << std::endl;
}
~Base(){
std::cout << "Destructor base" << std::endl;
}
Base& operator=(const Base& a){
std::cout << "Assignment base" << std::endl;
}
};
class Derived : public Base{
public:
};
int main ( int argc, char **argv ) {
Derived p;
Derived p2;
p2 = p;
return 0;
}
The output after compilation by g++ 4.6:
Constructor base
Constructor base
Assignment base
Destructor base
Destructor base
Why assignment operator of base class is called altough it is said that assignment operator is not inherited?
Actually, what is called is the implicitly defined operator =
for Derived
. The definition provided by the compiler in turn calls operator =
for the Base
and you see the corresponding output. The same is with the constructor and destructor. When you leave it to the compiler to define operator =
, it defines it as follows:
Derived& operator = (const Derived& rhs)
{
Base1::operator =(rhs);
...
Basen::operator =(rhs);
member1 = rhs.member1;
...
membern = rhs.membern;
}
where Base1,...,Basen
are the bases of the class (in order of specifying them in the inheritance list) and member1, ..., membern
are the members of Derived (not counting the members that were inherited) in the order you declared them in the class definition.
You can also use "using":
class Derived : public Base{
public:
using Base::operator=;
};
http://en.cppreference.com/w/cpp/language/using_declaration
I read this post several time before someone helped me with this.
You don't have a default
Derived& operator=(const Base& a);
in your Derived
class.
A default assignment operator, however, is created:
Derived& operator=(const Derived& a);
and this calls the assignment operator from Base
. So it's not a matter of inheriting the assignment operator, but calling it via the default generated operator in your derived class.
Standard says (12.8):
An assignment operator shall be implemented by a non-static member function with exactly one parameter. Because a copy assignment operator operator= is implicitly declared for a class if not declared by the user (12.8), a base class assignment operator is always hidden by the copy assignment operator of the derived class.
and then assignment operator of derived call your base
The implicitly-defined copy/move assignment operator for a non-union class X performs memberwise copy-/move assignment of its subobjects. The direct base classes of X are assigned first, in the order of their declaration in the base-specifier-list, and then the immediate non-static data members of X are assigned, in the order in which they were declared in the class definition.