1

Consider the following code:

#include "stdafx.h"
#include <iostream>

class Eelement {
public:
    static int m_iVal;
};

int Eelement::m_iVal = 33;

int main()
{
    //...
    return 0;
}

Question:
Why, during the initialization of the static variable m_iVal, I must to precede its name by its type int a second time (first time in class definition) ?

int Eelement::m_iVal = 33;

Why the compiler imposes this syntax which for me looks much more like a double declaration than other things because compiler already knows its type (from the definition of the Element class).

5
  • It's the same as with member functions, there can be only one definition. Commented Feb 12, 2020 at 9:12
  • static int ; should that be static int m_iVal; ? Commented Feb 12, 2020 at 9:17
  • @NutCracker Thank you for the link. The article discuss about this point. But something always worries me: if I write this: char Eelement :: m_iVal = 33; The compiler will tell me that the declaration is not compatible with int Element :: m_iVal therefore, it knows its type well ! Commented Feb 12, 2020 at 9:44
  • 1
    Two things are there 1) Declaration and 2) Definition Commented Feb 12, 2020 at 9:46
  • @Landstalker look at the answers in the duplicate question. The last answer shows the improvement introduced in C++17 : inline static Commented Feb 12, 2020 at 15:12

2 Answers 2

1
Eelement::m_iVal = 33;

is an assignment to the static member. The int is not superflous, because only this is a definition:

int Eelement::m_iVal = 33;
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks. But The compiler reports an error if I try to write: char Eelement::m_iVal = 33; and warns me of an incompatibility with the declaration int Element :: m_iVal If I suppose that the compatibility between "the declaration" and "the definition" must be always respected, type mention can be removed in the "second" definition. like that, we are sure that the compatibility of the type will be always respected.
But? I didnt imply that you can have a definition that does not match the declaration. Though still you cannot remove int in the example, because then it is not a definition
Yes I understood. it was in the continuity of my reflexion and not in direct relation to your explanation ;)
1

Why the compiler imposes this syntax which for me looks much more like a double declaration ...

It is not double declaration. Inside the class, it is declaration, but when you put:

int Eelement::m_iVal = 33;

outside of the class, it is definition. The declarations may happen in different translation units (TUs). By defining the static variable, you tell the compiler which translation unit to use for putting the static variable there.

1 Comment

Technically a definition is also a declaration.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.