I have a class that defines a function Setup
(just a name) behavior. This function is called in the constructor to initialize the variable.
class Base
{
public:
Base()
{
Setup();
}
const int& Value() const {return val_;}
void Print() const
{
std::cout << "My value is " << Value() << std::endl;
}
protected:
void SetValue(double v) {val_ = v;}
virtual void Setup() {SetValue(1.0);}
private:
int val_;
};
A class is derived from Base
to override the Setup
function
class Derived : public Base
{
public:
Derived() : Base() {}
protected:
void Setup() override {SetValue(2.0);}
};
So when Derived
is instantiated, I expected the variable to initialize to new value
Derived a;
a.Print();
It should print 2, but instead I get 1. I wonder why the Setup
of the derived class is not invoked in the constructor.