Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assignment operator inheritance

Tags:

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?

like image 692
scdmb Avatar asked Feb 06 '12 14:02

scdmb


People also ask

Are assignment operators 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.

What does assignment operator do in C++?

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.

What do assignment operators do?

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.


1 Answers

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.

like image 97
Armen Tsirunyan Avatar answered Sep 16 '22 14:09

Armen Tsirunyan