C++ logic

I'm having trouble understanding why it is printing these values out.
The answer is : A, B , ~B, ~A, A,B,~A

I understand the cout stuff, but I think I am just getting confused on the void main() part. Can anyone help out? Thanks!

What is the following code fragment printing?

struct A {
public:
A() { cout << "A\n"; }
~A() { cout << "~A\n"; }
}; ~B
class B : public A {
public: A
B() { cout << "B\n"; }
~B() { cout << "~B\n"; }
};
void main() {
if ( true ) { B b; }
A* a = new B;
delete a;
}
Last edited on
When a derived class object is constructed, the anonymous base class sub-object is constructed first. And when it is destroyed, the anonymous base class sub-object is destroyed at the end.

The destructor for A ought to be virtual; or else delete a ; won't destroy B.

And main() must return int.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
using std::cout ;

struct A 
{
   A() { cout << "A\n"; }
   virtual /* added */ ~A() { cout << "~A\n"; } 
};

struct B : public A 
{ 
    B() { cout << "B\n"; } 
    ~B() { cout << "~B\n"; } 
};

int main() // *** main must return int
{
    if ( true ) { B b; }
    A* a = new B;
    delete a;
}
could you explain everything? i still don't get it. thank you!
Topic archived. No new replies allowed.