Why do we declare a static variable in the class & definition outside the class?

We declare a variable staticin the class and initialize the variable outside the class, but we use the variable inside the function.

Anyone tell me the reason? Thanks at Advance

+4
source share
5 answers

I am not sure, but I suppose, because only variables are declared inside the class member variables. They are initialized through the constructor or other member functions.

This happens when an object is created. However, objects must not be created for static members. Therefore, they must be initialized outside the class.

EDIT:
, . , .

+5

- -.

, :

struct Example
{
    static int counter;
    Example() { counter++; }
};

Example, , Example::counter. . ? ++, Stroustrup , (.. .cpp) , , "" . -

// Only in one .cpp file
int Example::counter = 0;

(, , , , ).

+3

.

, .

+1

, . , .

, , , , .

, , , , cfront; , "static_members_of_everything.cpp" . , , .

+1

A declaration within a class only declares a variable in this area. The definition actually allocates memory.

You use it inside class functions because it is defined in this area. Initialization of static variables does not occur during object creation, but rather at application startup.

0
source

All Articles