简体   繁体   中英

Why is this the output of this program?

#include <iostream>
using namespace std;


class  A
{
public:
    A()
    {
        cout << "A ctor" << endl;
    }
    virtual ~A()
    {
        cout << "A dtor" << endl;
    }
    virtual void foo() = 0;
};
class  B : public A
{
public:
    B()
    {
        cout << "B ctor" << endl;
    }
    virtual ~B()
    {
        cout << "B dtor" << endl;
    }
    virtual void foo()
    {
        cout <<"B's foo" << endl;
    }
};
class  C : public A
{
public:
    C() {
        cout << "C ctor" << endl;
    }
    virtual ~C()
    {
        cout << "C dtor" << endl;
    }
    virtual void foo() {cout << "C's foo" << endl;
    }
}; 

int  main ()
{

    C *ptr = new C[1];
    B b;
    return 0;
}

This gives the following output:
A ctor
C ctor
A ctor
B ctor
B dtor
A dtor

I don't understand why this is happening. For example, I know that a new C object is being created, that's derived from A, so the A ctor runs first. Then the C ctor runs. And then I thought the C dtor runs, but for some reason the A ctor is running again.

  1. C is created, this constructs A (base class) and then C
  2. B is created, this constructs A (base class) and then B
  3. B is destroyed (goes out of scope), this destructs B and then A (base class)

C is never deleted, so it's leaked and the destructors are never called.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM