Search code examples
c++constantsstatic-constructor

How to initialize static const members of a class which has the same type as the class?


I have a class whose static const members have the same type as the class. I am getting an error that class isn't yet complete.

#include<iostream>

class Color
{
public:
    Color(unsigned char red, unsigned char green, unsigned char blue)
    : Red(red), Green(green), Blue(blue)
    {
    }
    
    Color(){}
    
    unsigned char Red, Green, Blue;
    
    static const inline Color White{255, 255, 255};
};

int main()
{
    std::cout << Color::White.Red;
}   

Either I can make them non-const but then it is error prone as then it can be changed. If I make them const then they must be defined where the declaration is.

I guess for this situation there is a need of static constructor.


Solution

  • You can use a "factory" static method. This generalizes nicely to more complicated use cases, and has the added benefit of making it possible to use White in constant expressions:

    #include <iostream>
    
    class Color
    {
      public:
        unsigned char red, green, blue;
    
        constexpr Color(unsigned char _red, unsigned char _green, unsigned char _blue)
            : red(_red), green(_green), blue(_blue) {}
        
        constexpr static Color White() { 
            return {255, 255, 255}; 
        };
    };
    
    int main()
    {
        constexpr auto red_value = Color::White().red;
        std::cout << static_cast<int>(red_value) << '\n';
    }