0
#include <iostream>

class A {
public:
    const int HP = 200;
    A(){
        std::cout << this->HP << std::endl;
    }
};

class B : public A {
public:
    B();
};

Constructing a B object will construct the A potion first. I expect to reinitialize HP so that B() can print new HP. Is this feasible for a base class const member ?
I need a member shared between base and child but to be constant in one instance of class, any suggestions?

wohlstad
  • 12,661
  • 10
  • 26
  • 39
Sprout
  • 11
  • 1
  • https://stackoverflow.com/questions/1423696/how-to-initialize-a-const-field-in-constructor – Renat Jan 26 '23 at 10:34
  • The only way is through some constructor of A, by design. Const member are usually a bad idea. In most cases, we have the wrong mental model of the const member. If you think a private member "should" be const, try making it non-const and project its value from change from the outside by the interface. https://www.youtube.com/watch?v=dGCxMmGvocE – alfC Jan 26 '23 at 10:40

1 Answers1

1

You can add a constructor to A (and if needed also to B) that accepts the value for the const int member.
Then when you invoke A constructor from B constructor via the initializer list, you can pass this const value to the base.

Code example:

#include <iostream>

class A {
public:
    const int HP = 200;
    A() {
        std::cout << this->HP << std::endl;
    }
//----vvvvvv----vvvvvv--
    A(int hp) : HP(hp) {
        std::cout << this->HP << std::endl;
    }
};

class B : public A {
public:
    B() {};
//----vvvvvv----vvvvv--
    B(int hp) : A(hp) {}
};


int main()
{
    B b1;
    B b2{ 99 };
}

Output:

200
99

Note: B can also be left as is (without an additional constructor), and pass the required const value to the base.

wohlstad
  • 12,661
  • 10
  • 26
  • 39
  • Thank you for your answer! Further, if there are several such variables in Class A, can Class B specify some variables for initialization, while other variables use the values of Class A? – Sprout Jan 26 '23 at 10:34
  • `B` is invoking `A` constructor in the initializer list (like `: A(hp)`). As long as there's a constructor for `A` that accepts some of the members, you can use it. – wohlstad Jan 26 '23 at 10:36
  • Is there a general approach? In this case, I may need to set many constructors for Class A. – Sprout Jan 26 '23 at 10:38
  • That depends on the case. I cannot specify any general approach. – wohlstad Jan 26 '23 at 10:41
  • Well, thank you anyway! – Sprout Jan 26 '23 at 10:45