C++ – Static Constant Members in a Class

c++constantsoopstatic

How do I declare static constant values in C++?
I want to be able to get the constant Vector3::Xaxis, but I should not be able to change it.

I've seen the following code in another class:

const MyClass MyClass::Constant(1.0);

I tried to implement that in my class:

static const Vector3 Xaxis(1.0, 0.0, 0.0);

However I get the error

math3d.cpp:15: error: expected identifier before numeric constant
math3d.cpp:15: error: expected ‘,’ or ‘...’ before numeric constant

Then I tried something more similar to what I'd do in C#:

static Vector3 Xaxis = Vector3(1, 0, 0);

However I get other errors:

math3d.cpp:15: error: invalid use of incomplete type ‘class Vector3’
math3d.cpp:9: error: forward declaration of ‘class Vector3’
math3d.cpp:15: error: invalid in-class initialization of static data member of non-integral type ‘const Vector3’

My important parts of my class so far look like this

class Vector3
{
public:
    double X;
    double Y;
    double Z;

    static Vector3 Xaxis = Vector3(1, 0, 0);

    Vector3(double x, double y, double z)
    {
        X = x; Y = y; Z = z;
    }
};

How do I achieve what I'm trying to do here? To have a Vector3::Xaxis which returns Vector3(1.0, 0.0, 0.0);

Best Answer

class Vector3
{
public:
    double X;
    double Y;
    double Z;

    static Vector3 const Xaxis;

    Vector3(double x, double y, double z)
    {
        X = x; Y = y; Z = z;
    }
};

Vector3 const Vector3::Xaxis(1, 0, 0);

Note that last line is the definition and should be put in an implementation file (e.g. [.cpp] or [.cc]).

If you need this for a header-only module then there is a template-based trick that do it for you – but better ask separately about that if you need it.

Cheers & hth.,

Related Question