tags:

views:

295

answers:

3

Can i declare member variable as const in class of c++?if yes,how?

+7  A: 

You can - you put const in front of the type name.

class C
{
     const int x;

public:
      C() : x (5) { }
};
Daniel Earwicker
+2  A: 

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)
    {     
    }
};
RichieHindle
That should give you a different error, as you gave declared i, without defining it. You will need a "int X::i;" somewhere.
James Curran
@James - not so, if the compiler is up to date enough to support inline static const members that are initialized where they are declared.
Daniel Earwicker
@James: I don't believe that's true for static const int - you don't actually need a separate definition because the compiler treats it as a true constant.
RichieHindle
It will give you an error if you use it for simple, other things. The following makes it give a linker error, most probably: `int const ` and `` requires a definition, because here `X::i` appears where not only constant expressions are allowed (that's however a defect of the standard - fixed already for c++1x!). Usually, there will be no error if you only immediately read its value.
Johannes Schaub - litb
+6  A: 

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;
};
anon