Reputation:
Can i declare member variable as const in class of c++?if yes,how?
Upvotes: 8
Views: 11632
Reputation:
You declare it as you would if it wasn't a member. Note that declaring a variable as const will have considerable effects on the way that the class is used. You will definitely need a constructor to initialise it:
class A {
public:
A( int x ) : cvar( x ) {}
private:
const int cvar;
};
Upvotes: 8
Reputation: 281405
Sure, the simplest way is like this if the value will be the same across all instances of your class:
class X
{
public:
static const int i = 1;
};
Or if you don't want it static:
class X
{
public:
const int i;
X(int the_i) : i(the_i)
{
}
};
Upvotes: 3
Reputation: 116654
You can - you put const in front of the type name.
class C
{
const int x;
public:
C() : x (5) { }
};
Upvotes: 18