Search code examples
c++non-staticdatamemberdata-members

Access non static data member outside class


Is it possible to access non static data members outside their class? Say you have an example like the following. I know it does not make much sense as an example, but I just want to understand how to access a non static data member. If the following is compiled it generates an error:

 C.h|70|error: invalid use of non-static data member ‘C::age’|

//C.h

class C{
  public:
    int age;
};
 int getAge();

//C.cpp

C::C()
{
    age  = 0;
}
int getAge(){
   return (C::age);
}

Solution

  • Non-static members are instance dependent. They are initialized when a valid instance is initialized.

    The problem with your example is that, it tries to access a non-static member through the class interface without first initializing a concrete instance. This is not valid.

    You can either make it static:

    class C{
    public:
        static int age;
    };
    

    which requires you to also define age before using at runtime by: int C::age = 0. Note that value of C::age can be changed at runtime if you use this method.

    Or, you can make it const static and directly initialize it like:

    class C{
    public:
        const static int age = 0;
    };
    

    In this case, value of C::age is const.

    Both of which will let you get it without an instance: C::age.