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.
This can be used in several ways. Examples: Declaring a variable to be const means that its value cannot change; therefore it must be given a value in its declaration: const double TEMP = 98.6; // TEMP is a const double. ( Equivalent: double const TEMP = 98.6; )
“static const” is basically a combination of static(a storage specifier) and const(a type qualifier). The static determines the lifetime and visibility/accessibility of the variable.
They mean exactly the same thing. You're free to choose whichever you think is easier to read. In C, you should place static at the start, but it's not yet required.
Static is a storage specifier. Const/Constant is a type qualifier. Static can be assigned for reference types and set at run time. Constants are set at compile-time itself and assigned for value types only.
If you have a way to add C++11
(or later) flag to your compiler, you would've been able to do:
ifndef SHAPE_H
#define SHAPE_H
class Shape
{
public:
static constexpr double pi = 3.14159265;
private:
double originX;
double originY;
};
#endif
Since C++11
you are able to use const expressions to types other than integral ones. This enables you to declare and define in place your constant variable.
Further details: https://en.cppreference.com/w/cpp/language/constexpr
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With