Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can const member variable of class be initialized in a method instead of constructor?

I have a class and want to create a const int variable but the value for the variable is not available to me in constructor of the class.

In initialization method of the class i get the value. Can I assign it in that method? As I am assigning it only once (as const says) why it isn't working?

Code is as Following [Just a ProtoType] :

File : A.h

Class A
{
  private :
  const long int iConstValue;

  public :
  A();
  initClassA();
}

File : A.cpp

A::A()
{
 //CanNot initialize iConstValue (Don't have it)
}

A::initClassA(some params)
{
 // calculation according to params for iConstValue
 iConstValue = (some value)
}

This is not working. Somebody has any Solutions?

NOTE : I Can not get value for iconstValue in constructor by any way as there are some restriction. So Please don't suggest to do that.

like image 918
Anwar Shaikh Avatar asked Jul 20 '12 08:07

Anwar Shaikh


People also ask

Can const variable be initialized in constructor?

To initialize the const value using constructor, we have to use the initialize list. This initializer list is used to initialize the data member of a class. The list of members, that will be initialized, will be present after the constructor after colon. members will be separated using comma.

Do const variables need to be initialized?

A constant variable must be initialized at its declaration. To declare a constant variable in C++, the keyword const is written before the variable's data type.

Are member variables initialized before constructor C++?

Const member variables must be initialized. A member initialization list can also be used to initialize members that are classes. When variable b is constructed, the B(int) constructor is called with value 5. Before the body of the constructor executes, m_a is initialized, calling the A(int) constructor with value 4.


1 Answers

A small example:

class A
{
public:
  A():a(initial_value_of_a()) {}

private:
  const int a;
  int initial_value_of_a() { return 5; /* some computation here */ };
};
like image 111
Mickael Avatar answered Nov 15 '22 04:11

Mickael