0
#include <iostream>
#include <string>
using namespace std;

class Base
{
public:
    Base()
    {
        cout << "Base"<<endl;
    }
    ~Base()
    {
        cout << "~Base"<<endl;
    }

};

class Child: public Base
{
public:
    Child()
    {
        cout << "Child"<<endl;
    }
    ~Child()
    {
        cout << "~Child"<<endl;
    }
};

int main()
{
    try
    {
        Child cc;
    }
    catch(...)
    {
    }

    return 0;
}

the general output will be

Base 
Child
~Child
~Base

But if something terrible or exception caught while Base is constructor ,then is it possible that the sequece will be :

Base 
~Base
Child
~Child

Can anyone write a demo to illustate this? C++ usually doesn't throw exception in the constuctor, but if it does, then could it leads to that output?

Thanks for all helping. I am not sure that in usually code ,this could happens. Is it possible in complicated Base constructor or something wrong or whatever,that will change the usual output ? If so, can anyone give me one example?

3
  • 1
    why can't you "write a demo to illustrate this" yourself? Commented Mar 28, 2013 at 14:46
  • I write some test code, but it seems C++ doesn't support stack rescroll, after got exception, the desctructor will not be called. Commented Mar 28, 2013 at 14:48
  • I write some test code, but after caught exception, the destructor will not be called. Is there a way to illustrate that if something wrong or exception happens while at constuctor Base , the output will be Base() ~Base() Child() ~Child(). Commented Mar 28, 2013 at 14:50

2 Answers 2

4

If a exception occurs in your Base class constructor no destructors are called.
Simply because there is no complete object that needs to be destroyed!

Can't help but quote Herb on this:

"It cannot die, for it never lived!"

Sign up to request clarification or add additional context in comments.

Comments

0
include <stdexcept>
Base()
{
    cout << "Base"<<endl;
    throw std::runtime_error("error");
}

2 Comments

He just wanted a test for it so he can find out himself experimentally
I tried you way, it seems that after B constructor calls, no other will be called.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.