Ad Code

Define and Declare Static Variables?

Can we define and declare static variable inside the class as well?


The class declaration should be in the class

class foo
{
    private:
        static int i;
};

But the initialization should be outside of the class.

int foo::i = 0;

But C++ allows the simplification of the above if the static member variable is of const int type (e.g. int, bool, char) then you can declare and initialize.

class foo
{
    private:
        static int const i = 42;
};
Reactions

Post a Comment

0 Comments