Access static variable from static function

14,854

You have declared your static variable, but you have not defined it.

Non-static member variables are created and destroyed as the containing object is created and destroyed.

Static members, however, need to be created independently of object creation.

Add this code to create the int MyClass::s:

int MyClass::s;

Addendum:

C++17 adds inline variables, allowing you code to work with a smaller change:

static inline int s;  // You can also assign it an initial value here
       ^^^^^^
Share:
14,854
Stan
Author by

Stan

Updated on June 05, 2022

Comments

  • Stan
    Stan almost 2 years

    It is very important that my function is static, I need to access and modify another static/non-static class member in order to print it out later. How can I do that?

    Flow

    • Class is initiated
    • Constructor sets variable to something using internal function that must be static
    • Some time later I print that variable

    Example code

    #include <iostream>
    
    class MyClass
    {
    public:
        static int s;
        static void set()
        {
            MyClass::s = 5;
        }
    
        int get()
        {
            return MyClass::s;
        }
    
        MyClass()
        {
            this->set();
        }
    };
    
    void main()
    {
        auto a = new MyClass();
    
        a->set(); // Error
    
        std::cout << a->get() << std::endl; // Error
    
        system("pause");
    }
    

    Error

    LNK2001: unresolved external symbol "public: static int MyClass::s" (?s@MyClass@@2HA)
    LNK1120: 1 unresolved externals