Swathi Appari
Swathi Appari

Reputation: 193

object's scope within destructor

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

Upvotes: 3

Views: 106

Answers (4)

Jeeva
Jeeva

Reputation: 4663

object b2 is defined inside the constructor (local) which means it will not be accessible outside the braces }. so your destructor doesnt have any clue about the existance of b2. Whereas b1 is created as a class member so that it is visible.

Read this to get understanding about scope

Upvotes: 0

Luchian Grigore
Luchian Grigore

Reputation: 258598

b2's scope is the block you declared it in, which is the constructor.

Upvotes: 0

Yakov Galka
Yakov Galka

Reputation: 72479

b2 is a variable local to the constructor. What you're trying to do is essentially equivalent to:

   void f()
   {
       B *b2=new B;
   }

   void g()
   {
       delete b2;  // error : undeclared identifier
   }

which I guess you understand why it doesn't work. (g has its own scope and its own set of local variables, disjoint from those of f.)

Instead, make b2 a member variable:

class D
{
   B *b1;
   B *b2;
   public:
   D()
   {
       b1 = new B;
       b2 = new B;
       cout<<"D's Constructor Invoked"<<endl;
   }
   ~D()
   {
       delete b1;
       delete b2;  // works!
       cout<<"D's Destructor Invoked"<<endl;
   }
};

Upvotes: 2

R. Martinho Fernandes
R. Martinho Fernandes

Reputation: 234444

Because it's a local variable in another function. It's the same reason the following doesn't compile:

void do_something() {
    int answer = 42;
    frob(answer);
}

void do_something_else_completely_unrelated() {
    answer = 23; // what? there's no "answer" in scope!
}

Upvotes: 1

Related Questions