Deepika Deepika - 1 year ago 63
C++ Question

C++ - Scope of the object created at the end of class definition

If I have a class like

class sample{
} obj;

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

Answer Source

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).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download