2

If I have a class like

class sample{
  // ...
} obj;

What is the scope of object obj created above? When will the object be destroyed?

iammilind
  • 68,093
  • 33
  • 169
  • 336
Deepika
  • 75
  • 4
  • then will the object be created in the heap? – Deepika Jul 21 '16 at 04:17
  • It will have whatever scope it is declared in, and will be created statically if global scope, or method-local if method scope. It will never be created on the heap. It will be destroyed when it goes out of scope. – user207421 Jul 21 '16 at 04:28
  • @iammilind Probably a duplicate, but not of that question. – user207421 Jul 21 '16 at 04:32
  • @EJP, yes you are right. In [this question](http://stackoverflow.com/q/9702053/514235), it doesn't discuss about `class` objects unfortunately. The other one I could find was [c++ global object](http://stackoverflow.com/questions/4918010/c-global-object) and [Global variables and scope - C++](http://stackoverflow.com/q/544462/514235). I am reopening the Q, see if you can close it. – iammilind Jul 21 '16 at 04:35
  • @iammilind No question about global scope is going to be an acceptable duplicate. The question is about what *is* the scope, which is context-dependent. – user207421 Jul 21 '16 at 04:39

3 Answers3

6

The scope of obj is the same as the scope of the class definition. If you define it outside of all functions, it's scope will be global and it will be created and initialized at static initialization time and destroyed as part of program termination.

However, it is also possible to define such an object in a function. In that case, it will be created when the function is entered and destroyed when the function returns.

void test()
{
   class sample{ }obj;
}

is perfectly valid code.

You can also define it as a nested type in a class. In that case, obj will be a member variable of the class. It will be created and destroyed with the construction and destruction of objects of the containing class.

struct Foo
{
   class sample{ }obj;
};

Also (thanks are due to @sjdalessandro for pointing it out), if the object is defined with global scope in a library and this library is loaded dynamically, then the object is created when the library is loaded (which is not necessarily when the program starts) and is destroyed when the library is unloaded (which is not necessarily when the program exits).

R Sahu
  • 204,454
  • 14
  • 159
  • 270
  • 3
    Besides that, if the object is defined with global scope in a library, and this library is loaded dynamically; then the object is destroyed when the library is unloaded; which is not necessarily when the program exits. –  Jul 21 '16 at 04:53
  • @sjdalessandro, excellent point. If you don't mind, I will add that to the answer. – R Sahu Jul 21 '16 at 04:59
  • Not at all. Be my guest. –  Jul 21 '16 at 05:06
2

It will have scope of the above scope declaration. Try it.

Example:

#include <iostream>

namespace A {
    namespace B {
        struct C {
            struct D {
                int e;  // variable e lifetime is same with struct D lifetime. Available only within struct D initialized
                D() : e(42) {}
            } d;    // variable d lifetime is samw with C struct lifetime. Available only within struct C initialized
            C() {}
            C(int v) {
                d.e = v;
            }
        } c;    // variable c lifetime is entire program. Scope is A::B::c
    }
}

int main() {
    // access variable with program lifetime in A::B namespace
    std::cout << A::B::c.d.e << std::endl;

    // create local variable of type A::B::C and access its fields
    A::B::C myc(55);
    std::cout << myc.d.e << std::endl;

    // declare struct F within main function scope and access its fields
    struct F {
        int g;
        F(int v) : g(v) { }
    } f (100);
    std::cout << f.g << std::endl;

    return 0;
}
1

It will have a global scope if the class is defined in a global scope. In that case the object obj will be initialized during application startup and will be destroyed during application exit. Otherwise, the scope will be limited to where the class is actually defined.

It is easy to observe this behavior. See below sample global definition of the class.

class sample
{
public:
    sample()
    {

    }   
    ~sample()
    {
    }
}Obj;

Put a break point in both Constructor and Destructor and see the point at which both are being invoked. You can observe the call stack such as given below when the Constructor in invoked, during application startup.

App.exe!sample::sample() Line 582   C++
App.exe!`dynamic initializer for 'Obj''() Line 589  C++
msvcr110d.dll!_initterm(void (void) * * pfbegin, void (void) * * pfend) Line 889    C
App.exe!__tmainCRTStartup() Line 460    C
App.exe!wmainCRTStartup() Line 377  C

From the above call stack it is evident that the constructor of the class sample is invoked as part of C++ runtime library initialization which occurs during application startup. The same is true for the class Destructor i.e. it will be invoked during application exit.

As @sjdalessandro pointed out, if the object is defined in a library, and this library is loaded dynamically, then the object is destroyed when the library is unloaded; which is not necessarily when the program exits.

MNS
  • 1,354
  • 15
  • 26
  • 1
    This is not necessarily correct; the scope of an object depends on where it's declared. If `Obj` is declared in a class, it will be scoped by an instantiation of the enclosing class, and if it's declared in a function, it will have function scope. – mkal Jul 21 '16 at 04:25
  • 1
    You should also delete your erroneous comments. – user207421 Jul 21 '16 at 04:32
  • 1
    Also, if the object is defined in a library, and this library is loaded dynamically, then the object is destroyed when the library is unloaded; which is not necessarily when the program exits. –  Jul 21 '16 at 04:34
  • @EJP I didn't get you. There is no comments in the code. As you know, the other one is the call stack shown inside debugger. – MNS Jul 21 '16 at 04:36
  • I didn't say anything about 'in the code'. There are not one but two erroneous comments by you under the question, that repeat the misinformation you initially posted in this answer. – user207421 Jul 21 '16 at 04:38