0
// CPP program to illustrate
// when not using static keyword

#include<iostream>
using namespace std;

class GfG
{
    int i;
    public:

        GfG()
        {
            i =0;
            cout<< "Inside Constructor\n";
        }
        ~GfG()
        {
            cout<< "Inside Destructor\n";
        }
};

int main()
{
    int x = 0;
    if (x==0)
    {
        static GfG obj;
    }
    cout << "End of main\n";
    cout << obj.i;

}

I have one question on the scope of static object 'obj'. When I compiled this code, it throws an exception "error: ‘obj’ was not declared in this scope"

I thought that when we call 'obj,' it stays until the function main closes down. Can someone explain why I can the error message above?

  • Summary of the linked duplicate: While your `obj` does, indeed, have a *lifetime* that is the duration of the whole program, its *scope* is the block in which it is declared. – Adrian Mole Apr 09 '22 at 22:43

0 Answers0