Search code examples
c++global-object

What is the need of global objects in c++?


I know that C++ also allows to create global objects of class and struct.

#include <iostream>
using std::cout;
class Test
{
    public:
        void fun()
        {
            cout<<"a= "<<a;
        }
    private:
        int a=9;
};
Test t;  // global object
int main()
{
    t.fun();
    return 0;
}

When & where should i use global objects? Is there any specific use of global objects? Please help me.


Solution

  • The short answer is there is no need.


    The long answer is that it can sometimes be convenient. Unfortunately convenience is subjective, and what one finds to convenient another might find to be too lenient.

    Global objects have issues (among which muddying data flows in the code and access synchronization), but sometimes one might find it convenient nonetheless to use one because it makes something easier. It can indeed remain easier, or it can prove a maintenance burden, but that only the future can tell...

    ... If you can avoid global objects, in general you should be better off. In practice, though, you will rarely encounter issues before programming at scale; for toy examples and students' projects there is rarely an issue, which is why beginners fail to understand why more seasoned developers avoid them like the plague.