7

Something.h

  1 class Something
  2 {
  3 private:
  4     static int s_nIDGenerator;
  5     int m_nID;
  6     static const double fudgeFactor;    // declaration - initializing here will be warning
  7 public:
  8     Something() { m_nID = s_nIDGenerator++; }
  9 
 10     int GetID() const { return m_nID; }
 11 };

foo.cpp

  1 #include <iostream>
  2 #include "Something.h"
  3 
  4 // This works!
  5 //const double Something::fudgeFactor = 1.57;
  6 
  7 int main()
  8 {
  9     Something cFirst;
 10     Something cSecond;
 11     Something cThird;
 12 
 13     const double Something::fudgeFactor = 3.14;
 14 
 15     using namespace std;
 16     cout << cFirst.GetID() << endl;
 17     cout << cSecond.GetID() << endl;
 18     cout << cThird.GetID() << endl;
 19     return 0;
 20 }

When trying to define the value of the static member variable of Class Something inside main, I encounter a compiler error as given below. Assigning a value outside the main() works fine. I understand that static member variables can be given a value only once, but why does assigning it outside a function versus inside a function matter?

$ clang++ foo.cpp foo.cpp:13:29: error: definition or redeclaration of 'fudgeFactor' not allowed inside a function const double Something::fudgeFactor = 3.14; ~~~~~~~~~~~^ 1 error generated.

Electrix
  • 510
  • 3
  • 14

2 Answers2

4

You are not assigning the variable inside the function; you are defining it (and initializing it). You can't do that inside the function because of scope rules. The variable is declared in the global (namespace) scope; therefore it also has to be defined in the namespace scope. It is not a local variable.

By the way, for static const variables, recent C++ standards allow you to initialize them at the point of declaration (as in your .h file) but you still have to define them, but this time without the initializer:

const double Something::fudgeFactor;
Klitos Kyriacou
  • 10,634
  • 2
  • 38
  • 70
  • 1
    you can, you have to use `constexpr` instead of `const` – Slava Nov 12 '15 at 22:24
  • Yes, you're right. Actually, I'm thinking of deleting this answer because your comment quite rightly points out the question is a duplicate, and we don't want to pollute SO with duplicates. – Klitos Kyriacou Nov 12 '15 at 22:25
-1

Static data members of a class needs to have external linkage. By this rule, the static members must be defined in namespace scope.

Mahesh
  • 34,573
  • 20
  • 89
  • 115