Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Definition or redeclaration not allowed inside a function [duplicate]

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.

like image 496
Electrix Avatar asked Nov 12 '15 22:11

Electrix


1 Answers

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;
like image 196
Klitos Kyriacou Avatar answered Nov 15 '22 12:11

Klitos Kyriacou