0

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.

kstn
  • 537
  • 4
  • 14
  • 2
    When `Base` is being constructed `Derived` does not exist. See [Virtual functions calls during construction and destruction](https://en.cppreference.com/w/cpp/language/virtual#During_construction_and_destruction). – Richard Critten Mar 16 '23 at 13:18
  • Unrelated: Do you know that the class have access to its own members ? It does not need to use accessors (getters/setters). For example, in the `Print()` function, you can directly use `val_`. – Fareanor Mar 16 '23 at 13:25
  • That's the way it is specified. If a constructor of `Base` calls a virtual function, then `Base`s version (not the version of a derived class) will be called. Part of the reason for that is that base class constructors are called BEFORE any members of a derived class are initialised, and that is before the derived class constructor is called. So there is no context in the base class constructor to permit calling the derived version of a virtual function. – Peter Mar 16 '23 at 13:31
  • And, for completeness, the same thing happens in **destructors**. – Pete Becker Mar 16 '23 at 13:39
  • `Derived() : Base() { SetValue(2.0); }` or add another Base constructor to support `Derived() : Base(2.0) {}` – Eljay Mar 16 '23 at 14:29

0 Answers0