c++classconstructordestructorclass-hierarchy

create a base class object use a derived class constructor c++


Is someone can tell why A a = B(); call constructor fisrt and then destructor immediately? And why the output like this?

C A

C B

D B

D A

test1 A

D A
class A  {
public:
    A() {
        cout<< "C A" <<endl;
    }

    ~A() {
        cout<< "D A" <<endl;
    }

    void test1() {
        cout<< "test1 A" << endl;
    }
};

class B:public A {
public:
    B() {
        cout<< "C B" <<endl;
    }

    ~B() {
        cout<< "D B" <<endl;
    }

    void test1() {
        cout<< "test1 B" << endl;
    }
};

int main(int argc, const char * argv[]) {

    A a = B();   
    a.test1();
    return 0;
}

Solution

  • In this declaration

     A a = B(); 
    

    there is at first created a temporary object of the type B. So its base constructor A and the constructor of B are called.

    C A
    
    C B
    

    The object a is created using the default copy constructor of the class A.

    After the declaration the temporary object of the type B is destroyed calling destructors in the reverse order

    D B
    
    D A
    

    At the end of the program the object a is also destroyed calling its destructor.

    test1 A
    
    D A