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

13,008

Solution 1

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 */ };
};

Solution 2

const doesn't mean you can only assign it once, you can never assign to a const object. A const variable is initialized once and its value cannot change. So you initialize it in the constructor, when all members and bases are initialized, then you can't change it after that.

If you can't get the value on construction you could either make the variable non-const, so you modify it, or maybe you could delay construction until you have all the data, using a placeholder until you construct the real object.

Two-stage construction is a code smell, it's certainly incompatible with const members.

Solution 3

You cannot do that, because you cannot change the value of a const variable. by the time initClassA runs the const data member has already been initialized (to some garbage value in this case). So you can only really initialize the data member to some value in the constructor initializer list.

If you want to set the variable only once, then you can make is non-const, and add a guard so it can only be set once. This isn't pretty but it would work:

class A
{
  private :
   long int iValue;
   bool isInitialised;

  public :
  A() : iValue(0), isInitialized(false);
  bool initClassA() {
    if (isInitialized) return false;
    iValue = something:
    isInitialized = true;
    return true;
  }
}

But it isn't good practice to have objects that can be initialized or not. Objects should be in a coherent state when constructed, and clients should not have to check whether these objects are initialized.

Share:
13,008
Anwar Shaikh
Author by

Anwar Shaikh

Updated on June 04, 2022

Comments

  • Anwar Shaikh
    Anwar Shaikh almost 2 years

    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.