Search code examples
c++classstaticconstants

Private Static Constexpr Member Variable is Inaccessible in Main?


In my Environment class I have a private static member variable:

class Environment {
public:
    // ...

private:
    std::vector<Part> objects;
    Color background_color;
    
    //ERROR:
    static constexpr Color default_background_color = Color({ 210, 210, 210 });
};

And in main I am trying to access that variable:

int main() {
    // ERROR: 'member "Environment::default_background_color" is inaccessible'
    Environment environment(0.1, Environment::default_background_color); 
}

So my question is, what is wrong and how do I make a const static variable that I can access outside of the Environment class?


Solution

  • Your data member is declared private (and NOT static, BTW), so it is simply not accessible to any code outside of the class.

    If you want main() to access the member, either:

    • declare the member as public (and static):
    class Environment {
    public:
        Environment(double air_density, Color background_color);
        ...
        static constexpr Color default_background_color = Color({ 210, 210, 210 });
        ...
    };
    
    int main() {
        Environment environment(0.1, Environment::default_background_color); // OK
        ...
    }
    

    Online Demo

    • declare main() as a friend of the class:
    class Environment {
    public:
        Environment(double air_density, Color background_color);
        ...
    private:
        ...
        static constexpr Color default_background_color = Color({ 210, 210, 210 });
    
        friend int main();
    };
    
    int main() {
        Environment environment(0.1, Environment::default_background_color); // OK
        ...
    }
    

    Online Demo