Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access static variable from static function [duplicate]

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
like image 325
Stan Avatar asked Feb 15 '13 18:02

Stan


1 Answers

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
       ^^^^^^
like image 133
Drew Dormann Avatar answered Oct 17 '22 15:10

Drew Dormann