user1799323
user1799323

Reputation: 659

Member variable in C++ class that is always constant for all objects of that class?

I'm constructing a class where I have three member variables that I want to always be the same value NO MATTER WHAT.

I have

class foo{

public:
    double var_1, var_2, var_3;
    double x=1, y=2, z=3;

[functions go here]

};

that gave me an error since I can't initialize a variable like that. But I want x, y and z to always be 1, 2 and 3 respectively. I tried defining them outside the class but that doesn't work since I want them to be member variables of the class.

How do I do this?

Upvotes: 2

Views: 1363

Answers (3)

ChrisF
ChrisF

Reputation: 137148

You don't have to make them static. You could declare them like this:

class foo{

public:
    double var_1, var_2, var_3;
    const double x=1.0;
    const double y=2.0;
    const double z=3.0;

[functions go here]

};

Though if they are integer values then declaring them as ints would be better.

Upvotes: 1

Syntactic Fructose
Syntactic Fructose

Reputation: 20084

make these values static for the class, this way all object will inherit these same values.

static const int x = 1;
static const int y = 2;
static const int z = 3;

through technically, this does not define the variable. If a static data member is of const integral or const enumeration type, you may specify a constant initializer in the static data member's declaration. This constant initializer must be an integral constant expression. Note that the constant initializer is not a definition. You still need to define the static member in an enclosing namespace.

#include "foo.h"
#include <//libs....>
int foo::x;
int foo::y;
int foo::z;
//class functions down below

Upvotes: 4

ravuya
ravuya

Reputation: 8766

You can also use an initializer list in the constructor to set these fields' initial values, just as with any other member:

class foo {
public:
    const double x;
    const double y;
    const double z;

    foo() : x(1), y(2), z(3) {
    }
};

Upvotes: 3

Related Questions