Search code examples
c++classinitializationprivate

Initialize private access variable


InC++, is it valid to initialize a private access variable outside of the class definition like this?

class Test
{
    private: int a;
    public:  int b;
}

int Test::a = 1;

Solution

  • The example in your question is not valid. If the member variable is static you can initialize it like you do in your example. If the member variable is not static you should initialize in in either the constructor or class definition.

    It also does not matter what the access privilege is and the variables are initialized the same way regardless if they are public, protected, or private .

    struct Foo
    {
        Foo() : a{1} // ctor-initializer
        {
            b = 2; // ctor body
        }  
        int a;
        int b;
        int c = 3;  // At definition.
    };