Home > database >  Why don't we have to declare static functions the same way we need to declare static variables
Why don't we have to declare static functions the same way we need to declare static variables

Time:04-22

Consider the following struct:

struct Toto {
    static int a;

    static void Print() {
        std::cout << a;
    }
};

And the following main function using the struct in the same cpp file (main.cpp):

int main()
{
    Toto::Print();
}

Building this gives the following error:

Error LNK2001 unresolved external symbol "public: static int Toto::a"

I understand from https://en.cppreference.com/w/cpp/language/static that

Static members of a class are not associated with the objects of the class

And thus, I've been told we have to declare the variable Toto::a outside the struct, in the transaction unit as follow:

int Toto::a;

From the same source it says that

Static member functions are not associated with any object.

And that

Static data members are not associated with any object.

Why do I have to declare static variables but not static functions? Is the call in itself a declaration? If not, what else allow me to bypass that declaration?

CodePudding user response:

Static member functions are ordinary functions at the assembly level. The difference is only the hidden pointer 'this' that does not exist in them. They are basically global functions that exist like any other non static or non member (and not inline) function within the C scope of a class name. Function scopes are C thing, they are not there at the CPU level.

Static variables are different. They exist before any class object is created. They are not created when a class instance is created. They are there as globals.

Perhaps it's done the way it's done to emphasize that difference.

  • Related