-1

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;
}
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
xxbzzzz
  • 13
  • 2
  • [What is Object Slicing ?](https://stackoverflow.com/questions/274626/what-is-object-slicing) – Mahesh Apr 29 '22 at 22:46

1 Answers1

1

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
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335