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

前端 未结 5 1084
南方客
南方客 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

    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.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-02-10 08:06

    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 */ };
    };
    
    0 讨论(0)
  • 2021-02-10 08:12

    Maybe what you can do, is change for a int pointer, receive this pointer in your constructor, and change the pointer where you want :P

    But it will not be the same functionnality cause it will be the pointer which is const and not anymore the value :/

    0 讨论(0)
  • 2021-02-10 08:24

    I think I need to change the design and I should calculate the (or get) the const variables value at constructor any how. As there is no way I can set it's value later.

    0 讨论(0)
提交回复
热议问题