Search code examples
c++classvariablesprotected

Is there a way to declare a C++ protected variable from outside it's class?


class A {
public:
    A();
    int get();
    void set();
};

protected int A::var;

seems like it would work. However, it "expects an unqualified-id before protected". What's the correct way to do this?


Solution

  • How would the compiler know how much space to allocate for instances of the class? Consider

    A foo;
    protected int A::var;
    A bar;
    

    How would the compiler know to allocate space for var when it allocated foo? The first and second lines could even be in different translation units.

    So, no, it's not possible because it doesn't make sense.