Is this the proper way to use a static const variable? In my top level class (Shape)
#ifndef SHAPE_H
#define SHAPE_H
class Shape
{
public:
static const double pi;
private:
double originX;
double originY;
};
const double Shape::pi = 3.14159265;
#endif
And then later in a class that extends Shape, I use Shape::pi. I get a linker error. I moved the const double Shape::pi = 3.14… to the Shape.cpp file and my program then compiles. Why does that happen? thanks.
Because
const double Shape::pi = 3.14159265;is the definition ofShape::piand C++ only allows a single definition of a symbol (called the one-definition-rule which you may see in it’s acronym form ODR). When the definition is in the header file, each translation unit gets it’s own definition which breaks that rule.By moving it into the source file, you get only a single definition.