There is this code:
#include
class Base {
public:
Base(){
std::cout << \"Constructor base\" << std::endl;
}
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.
That is because the default assignment operator created calls it's base assignment operator, i.e. it isn't inherited but still called as part of the default assignment operator.
Assignment operator is indeed not inherited. Inheriting that operator would enable you to assign a Base
to a Derived
, however Base b; p = a;
will (rightfully) fail to compile.
What happens is that the compiler generates an operator=
, since you haven't defined a custom one for Derived
. The autogenerated operator=
will call the assignment operators of all all base classes and all members. In that aspect it is much the same as constructors/destructors, which also call the respective function on all Bases/members.
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.