Search code examples
c++inheritanceinitialization

Why is the Base class data initialized before Derived class data


Consider this code:

class Base {
public:
  Base(): m_i{10} {}
private:
  int m_i;
};

class Derived: public Base {
public:
  Derived(): m_f{100.0} {}
private:
  float m_f;
};

int main() {
  Derived d;
}

When Derived d; is instantiated C++ first calls Base() constructor and initializes Base's data - m_i - and only then calls Derived() constructor and initializes Derived's data - m_f.

But what is the reason for it?

Why C++ doesn't do it the other way?

Because, from what I can tell, it isn't faster or something.


Solution

  • 1) The main reason for it is - Derived class should have access to Base class fields.

    Let me explain with an example:

    class Base {
    public:
      Base(): m_i(10) {}
    protected:
      int m_i;
    };
    
    class Derived: public Base {
    public:
      Derived(): m_f(100.0) {
        m_i = 1;
      }
      void print() {
        std::cout << "Derived m_f=" << m_f << ", m_i=" << m_i << '\n';
      }
    private:
      float m_f;
    };
    
    int main() {
      Derived d;
      d.print(); // prints: "Derived m_f=100, m_i=1"
    }
    
    

    If the initialization happened the other way around Derived could access uninitialized data in Base, which is bad.

    Also Derived() constructor wouldn't have the ability to change the Base field values correctly and you would get "Derived m_f=100, m_i=10" printed, because m_i=1; in Derived() would happen first and m_i{10} would happen next and it simply looks confusing.

    2) I can think about the other reason as well:

    Imagine the following - Base() constructor throws the exception and have to clean up after himself.

    If we already initialized Derived it would mean that we now have to clean up after Derived too, which is overhead.