Brykyz
Brykyz

Reputation: 657

Static member of class with private constructor

I'm making class, that should help with minor deficiencies of C++, like comparing double with other double with defined precision, and so on.

I have namespace Utilities, where class Double exists:

namespace Utilities {

void init();

class Double {
public:
    //! @brief Compares the equality of two doubles with defined precision
    static bool fuzzyCompare(const double &d1,const double &d2);

    static void setFuzzyComparePrecision(int precision);
private:
    //! @brief Private constructor
    Double() {};

    static int fuzzyComparePrecision_;
};

}

I want this class to contain only static members and not be instantiable. Current idea is to call Utilities::init() function in void main(), which initializes default values for members of class Double.

Is it possible to set default fuzzyComparePrecision_ without calling function init() in void main()? Or in other words, is it possible to set default value of fuzzyComparePrecision_ without instance of Double and without calling other function such as init()?

Thanks for your help!

Upvotes: 0

Views: 1153

Answers (2)

Yksisarvinen
Yksisarvinen

Reputation: 22176

It's not only possible, it's (almost) required to do so.

Starting from C++17, you can declare any static variable as inline, and initialize it in class body:

class Double {
private:
    inline static int fuzzyComparePrecision_ = 0;
};

Before C++17, every* static class member requires an out-of-class definition.

It can (and usually should) be combined with initialization, to avoid dealing with uninitialized variables.

You have to provide the following (in cpp file):

int Utilities::Double::fuzzyComparePrecision_;

But you can also extend it with initialization:

int Utilities::Double::fuzzyComparePrecision_ = 0;

*There are exceptions - const static members can be initialized in class body with another constant expression.

Upvotes: 2

user11313931
user11313931

Reputation:

To initialize static member variables you have two ways:

  1. If you are using C++17 you can do this with inline static member variables:
    class Double {
    private:
        inline static int fuzzyComparePrecision_ = 2;
    }
    
  2. For earlier version of C++ you have to do it outside the class declaration in a source file (it can't be in a header file):
    class Double {
    private:
        static int fuzzyComparePrecision_;
    }
    
    int Double::fuzzyComparePrecision_ = 2;
    

Upvotes: 2

Related Questions