Tagger5926
Tagger5926

Reputation: 442

Declaring and defining class static member variable does not result in multiple declaration, why is this?

I would like to know why declaring a static variable and then defining it in a source file not cause a multiple declaration compiler error. Below is a trivial example of what I mean.

// header.hpp
class Foo
{
public:
static int my_var; // declare
};
// source.cpp
#include "header.hpp"
int Foo::my_var = 5; // define

Why does my_var not cause a multiple declaration compiler error?

Also, would the following example code not cause an error for the same reason as above?

// Class.hpp
class Foo
{
...
};

#include "Class.hpp"
class Foo; // Forward declare, no multiple declaration?

Thanks in advance.

Upvotes: 0

Views: 70

Answers (2)

R Sahu
R Sahu

Reputation: 206607

As you pointed out,

static int my_var; // declare

is a declaration. It is a declaration of the static membr variable of the class.

and

int Foo::my_var = 5; // define

is the definition of the static member variable of the class. There is no reason that should be an error.


As to

class Foo
{
...
};

#include "Class.hpp"
class Foo;

That is perfectly fine.

You can declare a name, in this case a class, as many times as you want as long as there is no conflict.

The language is quite flexible for declarations.

You can use:

class Foo { ... };

class Foo;
class Foo;
class Foo;
class Foo;
class Foo;
class Foo;
class Foo;

without any problem.

You may even use:

class Foo { ... };

int Foo;

as long as you are careful with your use of Foo the class and Foo the variable.

int main()
{
   class Foo f1; // OK. f1 is of type class Foo
   Foo = 10;     // OK. Foo is the variable.
   Foo f2;       // Not OK. Foo is the variable not the class
}

Upvotes: 3

liakoyras
liakoyras

Reputation: 1185

When you are creating the class, you state (declare) that there is a member variable. Later you can change its value to be whatever you like (define) (explicitly like in your example or through a function) in whatever part of your code.
Declaring a variable just warns the compiler that a certain variable will be used, and later you can choose whether to give it a value or not.
Because you define it as static, all objects of the class are going to share the same value for this variable.
It is considered good practice in general to define/initialize your static variables when you declare them, otherwise (even if you don't cause a compiler error), your code may nit work as expected.

Upvotes: 0

Related Questions