S
S
Sazoks2019-11-04 10:59:52
OOP
Sazoks, 2019-11-04 10:59:52

Order of calling constructors when inheriting?

Hello.
I'm not entirely clear in what ORDER the constructors are called when inheriting?
Example:

#include <iostream>
using namespace std;

class Parent
{
public:
  int m_Id;

  Parent(int Id = 0)
    : m_Id(Id) 
  {
    cout << "Parent\n";
  }

  int GetId() const { return m_Id; }
};

class Child : public Parent
{
public:
  double m_Value;

  Child(double Value = 0.0)
    : m_Value(Value)
  {
    cout << "Child\n";
  }

  double GetValue() const { return m_Value; }
};

int main()
{
  Parent p;
  Child c;
  return 0;
}

I understand that when creating a Child c, the Parent part is created first, and then the Child part.
But in what order? First the Child constructor is called, then the Parent constructor, and then the Child constructor continues to execute? Or when creating Child c IMMEDIATELY Parent () is called, and already after Child () is called?
I hope I've made myself clear
. Thank you all.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Mercury13, 2019-11-04
@Sazoks

The call to the Parent constructor is considered part of the call to the Child constructor. And it happens before the construction of all fields added to Child - and even more so before the body of Child::Child.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question