Search code examples
c++initializationdeclarationstatic-methodsstatic-members

Is it possible to initialise a static member in a static method of a class in C++?


So I have the static member precision and a public static method to set its value in my class (the code below is stripped down a lot).

class Foo {
private:
    typedef unsigned short precision_t;
    static precision_t precision;
public:
    static void set_precision(precision_t value) {
        precision_t precision = value;
        /* other stuff */
    }
    
    static precision_t get_precision() {
        return precision;
    }
};

When I create an instance and then set the value, it seems to work fine, but trying to get the value gives a slightly cryptic error: main.cpp:(.text._ZN3Foo13get_precisionEv[_ZN3Foo13get_precisionEv]+0x7): undefined reference to `Foo::precision' collect2: error: ld returned 1 exit status (run on onlinegdb.com).

Exact code in main:

Foo *foo = new Foo(); //fine
foo->set_precision(5); //no error, but probably wrong given undefined reference
std::cout << Foo::get_precision(); //shows above error

My original code for set_precision looked more like

static void set_precision(precision_t value) {
    static bool defined = false;
    if (defined) {
        precision = value
    } else {
        precision_t precision = value;
        defined = true;
    }
    /* other stuff */
}

so it would initialise precision the first time only.

I also attempted to do this for the vector which stores pointers to all of the instances instead of having to write the code to initialise outside of the class/in the .cpp file.

Is it even possible to do this or do I have to initialise (the vector storing the instance pointers and the unsigned short storing the current precision) in the .cpp file before the main function?


Solution

  • Updated code:

    #include <iostream>
    using namespace std;
    
    class Foo {
    private:
        typedef unsigned short precision_t;
        static inline precision_t precision; 
        //static precision_t precision; //when not using static inline
    public:
        static void set_precision(precision_t value) {
            //precision_t precision = value; //<<-- error in your code
            precision = value; 
            /* other stuff */
        }
        
        static precision_t get_precision() {
            return precision;
        }
    };
    
    //Foo::precision_t Foo::precision = 0; //when not using static inline
    
    int main() {
        Foo *foo = new Foo(); //fine
        foo->set_precision(5); //no error, but probably wrong given undefined reference
        std::cout << Foo::get_precision(); //shows above error
        return 0;
    }