Search code examples
c++global-variables

About global variables


Consider two code snippets as below:

Case I:

class A {
    int globalOrLocal;
    funcA1() {…}
    funcA2() {…}
}

Case II:

int globalOrLocal;
class B {
    funcB1() {…}
    funcB2() {…}
}

Out of Case I and Case II above, which declaration of variable globalOrLocal can be called global? I think both, since they are defined outside all the functions due to which this variable would be stored on the heap. But I am not sure. Online resources give trivial examples without any involvement of classes. Could someone please help solve my doubt?

Thanks.


Solution

  • In Case I globalOrLocal is not a global variable. It is a private member variable of class A. An instance of it will be constructed for each instance of A that you construct and will be destroyed along with A when it is destroyed.

    In Case II you (potentially) have a global variable. Depends on whether there is an anonymous namespace wrapping it or another class holding it and class A as members/nested class.