I am trying to understand Destructor. I got following issue. Here in the below snippet why the object b2 is out of scope for Destructor ?
class D
{
B *b1;
public:
D()
{
b1 = new B;
B *b2=new B;
cout<<"D's Constructor Invoked"<<endl;
//delete b2;
}
~D()
{
delete b1;
delete b2; // error : undeclared identifier
cout<<"D's Destructor Invoked"<<endl;
}
};
B is just a simple class.
Thanks
b2is a variable local to the constructor. What you’re trying to do is essentially equivalent to:which I guess you understand why it doesn’t work. (
ghas its own scope and its own set of local variables, disjoint from those off.)Instead, make
b2a member variable: