class A
{
public:
virtual void f(){ printf("A.f "); }
~A(){ f(); }
};
class B : public A
{
A a;
public:
void f(){ printf("B.f "); }
B(){ throw -1; }
~B(){ f(); }
};
int main()
{
try{ B b; }
catch(...){ printf("Exc");}
}
So here’s how I see it. Inside the try block, nothing is being printed while constructing B b;. The block ends. I think compiler is destructing the A a; member first. So A.f() would be printed. Does that mean the destruction of class B instance is finished? After that, would compiler simply call ~A() (destructing base class)?
I thought I should’ve got A.f(), then B.f() (destructing class B instance) and after that A.f() again (destructor of base class). Compiling this made me think a little.
Exc is being printed at the end of course.
I’ve gone through several topic and haven’t found anything.
EDIT: Output from Dev-C++ (GCC 3.4.2) is
A.f A.f Exc
You really have two
Aobjects here.Binherits fromA, so a base class object ofAis instantiated first before B is.Ainstance is created as you have a member field of typeAas part ofB.When you create
B b, you create the base classA, and also the instanceA a.However, you then throw the exception in
B‘s constructor, so then all fully-constructed objects at that point are destructed, that is.~A()is called on the instanceA a.~A()is called on the base classA.That would explain why you get
A.f A.f Exc.B‘s destructor would not be called becauseBwasn’t fully constructed as its constructor did not finish successfully.