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).

Build Succeeded
  • 1,153
  • 1
  • 10
  • 24
Landstalker
  • 1,368
  • 8
  • 9

2 Answers2

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.

TonySalimi
  • 8,257
  • 4
  • 33
  • 62
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;
463035818_is_not_an_ai
  • 109,796
  • 11
  • 89
  • 185
  • 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. – Landstalker Feb 12 '20 at 10:00
  • 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 – 463035818_is_not_an_ai Feb 12 '20 at 10:57
  • Yes I understood. it was in the continuity of my reflexion and not in direct relation to your explanation ;) – Landstalker Feb 12 '20 at 11:39