Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
231 views
in Technique[技术] by (71.8m points)

c++ - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...