-1

I know that whenever an object goes out of scope or deleted compiler automatically calls destructor , but how do I know the scope of an object ?

For e.g. in this code:

    #include<iostream>
using namespace std;

class demo
{
    static int count;
public:
    demo()
    {
        cout<<"object created"<<++count<<endl;
    }
    ~demo()
    {
        cout<<"object destroyed"<<count--<<endl;
    }
};
int demo::count;
int main()
{
    cout<<"in main\n";
    demo d1;
    {
        cout<<"in block 1\n";
        demo d2;
        {
            cout<<"in block 2\n";
            demo d3;
        }
    }
    {
        cout<<"in block 3\n";
        demo d4;
    }
    cout<<"exit\n";
}

What is the scope of each object?

bhukamp
  • 1
  • 1
  • 1
  • did you try actually compiling and running this code? – fukanchik Jul 15 '16 at 05:41
  • 1
    http://stackoverflow.com/questions/10080935/when-is-an-object-out-of-scope – Balu Jul 15 '16 at 05:43
  • Doing this by order: The constructors get called: demo d1 -> demo d2 -> demo d3 -> demo d4. The destructors get called: -> demo d3 -> demo d2 -> demo d4 -> demo d1. The reason that happens, it's because each { } has its own set of start and finish addresses on the stack frame. Every time you meet a new object, it gets created under the necessary scope ( { } ). When you leave that scope, it gets called by the destructor (unless it was allocated, or configured as a static variable.) So the outputs of each one : – Noam Rodrik Jul 15 '16 at 05:49
  • Constructors && Destructors Combined-> object created 1 object created 2 object created 3 object destroyed 3 object destroyed 2 object created 2 (Means object 4) object destroyed 2 (Means object 4) object destroyed 1 Out of just looking at the code, maybe something wrong here or there. – Noam Rodrik Jul 15 '16 at 05:49

2 Answers2

1

The scope of an object is when it leaves the { } in which it has been declared. This is for local variables, not for static and global one.

In your ecample, the objects will leave the scope in this order: d3 d2 d4 and d1. Plese remark that d1 and d4 are in the same scope and the rule for deleting the objects in same scope is in inverse order of the allocation.

meJustAndrew
  • 6,011
  • 8
  • 50
  • 76
0

The objects in C++ can be created either on the stack or on on the heap.

A stack frame (or scope) is defined by a statement. That can be as big as a function or as small as a flow control block (while/if/for etc.). An arbitrary {} pair enclosing an arbitrary block of code also constitutes a stack frame. Any local variable defined within a frame will go out of scope once the program exits that frame. When a stack variable goes out of scope, its destructor is called.

When it is created in heap, it should be destructed by calling "delete" on the object

Taken from the post

Balu
  • 2,247
  • 1
  • 18
  • 23