Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static const double in c++

Tags:

c++

static

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.

like image 470
Crystal Avatar asked May 05 '10 23:05

Crystal


People also ask

What does const double mean in C?

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; )

What is static const in C?

“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.

Is it static const or const static?

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.

What is static vs const?

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.


1 Answers

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

like image 82
Benjamin Avatar answered Sep 29 '22 15:09

Benjamin