Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

For more complicated use cases, you can use a "factory" static method. This 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';
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading