Please consider the following mini example
// CFoo.hpp
class CFoo{
private:
static const double VPI = 0.5;
public:
double getVpi();
};
// CFoo.cpp
#include "CFoo.hpp"
double CFoo::getVpi(){
double x = -VPI;
return x;
}
// main.cpp
#include "CFoo.hpp"
int main(){
CFoo aFoo();
return 0;
}
Lining the program with gcc version 4.5.1 produces the error CFoo.cpp: undefined reference to CFoo::VPI. The error dose not occur if
- VPI is not negated
- the negation is written as
double x = -1 * VPI; - Declaration and definition of class CFoo happen in the same file
Do you know the reason for this error?
There are multiple problems with your code. Primarily, this is not valid C++03:
The declaration of a static data member can specify a constant initializer if and only if that initializer is
constintegral orconstenumeration type.0.5is neither of these, and hence your code is not valid C++. 9.4.2 Static data members covers this:In order to initialize
VPI, you must do so in the CPP file:header:
cpp :
Another problem, unrelated, is here:
The expression
CFoo aFoo();doesn’t do what you think it does. You think it declares an objectaFooof typeCFooand initializes it usingCFoo‘s default constructor. But what it actually does is declare a function namedaFootaking no parameters, returning aCFooby value. This is known as the most vexing parse. In order to do what you want, simple omit the parenthesis: