setting value of a constant in the constructor

Hi guys.

In my program, the value of a variable in a class of mine is defined in the constructor and is never changed afterward. Is there a way places that value in a constant or something of that sort?

Thanks.
1
2
3
4
class Foo
{
   static const int Bar = 5;
};


Makes Bar the constant value 5 across all instances of Foo.
This is not what I meant. I want to do something of that sort:

header file

1
2
3
4
5
6
7
8
9
class Foo

{
        static const int bar;
   public:
       Foo();
       Foo(int barIn);
       ~Foo();
}


class file

1
2
3
4
5
class Foo{
    Foo(int barIn){
       Bar = BarIn;
    }
}


I this won't work. But is there a way to do something similar?

thanks
Foo::Foo(int barIn):Bar(barIn){}
After : you can call at the constructors of your members
Last edited on
ne555, I'm sorry, I don't know what to do with that? Should I place this in the function that create Foo?
1
2
3
4
5
class file :
Foo::Foo(int BarIn)
{
     bar = barIn;
}


like this bro ?
but I cannot simply assign bar a new value, it is const.
if the value is static const, do as jsmith suggested.

if the value is non-static const, use an initializer list:

1
2
3
4
5
6
7
8
9
class Foo
{
  const int bar;

  Foo(int barIn)
    : bar(barIn)  // initializer list
  {
  }
};


Note the difference between static const and just const.
thank you, thank you, thank you.

that worked perfectly.

thank you all, I know can also understand what the previous guys meant.

Topic archived. No new replies allowed.