#include <iostream>
using namespace std;
class A{
int b;
public:
A(){
cout<<"Constructor for class A called\n";
b = 6;
}
~A(){
cout<"Destructor called for class A\n";
}
};
class B{
A a;
public:
B(){
cout<<"Constructor for class B called\n";
}
~B(){
cout<<"Destructor called for class B\n";
}
};
int main(void){
B obj1;
return 0;
}
When the above code is executed the constructors for both A and B are called as expected but when B’s object i.e. obj1 goes out of scope only B’s destructor is called. Why A’s destructor is not called even though A’s obj is one of the members of B ?
You’re missing a
<in A’s destructor:If you’re not getting a compilation error for the expression:
well, your compiler is trying to compare
coutto aconst char*. Which is a weird thing to do. But, alas, change<to<<and it should work: http://ideone.com/8TDyy