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?
In C++, like other functions, assignment operator function is inherited in derived class. For example, in the following program, base class assignment operator function can be accessed using the derived class object.
Assignment operators are used to assigning value to a variable. The left side operand of the assignment operator is a variable and right side operand of the assignment operator is a value.
The assignment operator = assigns the value of its right-hand operand to a variable, a property, or an indexer element given by its left-hand operand. The result of an assignment expression is the value assigned to the left-hand operand.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With