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

前端 未结 5 1083
南方客
南方客 2021-02-10 07:56

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

5条回答
  •  北海茫月
    2021-02-10 08:02

    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.

提交回复
热议问题