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

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

提交回复
热议问题