Alex Rivera | Logout

Static Variable initialisation for Classes in C++, why include data type?

Asked 2013-07-17T07:46:08.777
11

I've been learning C++, and I've come across static variable (I have prior knowledge from C89), and in the resource i'm using, they've declared a static variable in a class such as:

class nameHere
{
    public:
        static int totalNum;
}

int nameHere::totalNum = 0;

int main()
{}

For Example. What I don't understand is that, since I've already declared that the static variable is an integer in the class definition, why do I need to also declare it as an integer outside of the class definition? Would it not make sense to simply initialise it like so:

nameHere::totalNum = 0;

int main()
{}

Is there a particular reason or simply a convention of C++? Thanks for all the help!

Edit
Report

1 Answer

2

There is a difference between a definition and a declaration. While the static variable in the class has been declared, it has not been defined. The One Definition Rule, explains declarations and definitions and states

In any translation unit, a template, type, function, or object can have no more than one definition. Some of these can have any number of declarations.

Therefore, the full type of the object must be used when declaring the variable.

answered 2013-07-17T08:03:36.077

Your Answer