Loading lessons...
Constructors in Derived Classes & Initialization Lists
Constructors in Derived Classes & Initialization Lists
Constructors are not inherited, yet a derived object contains a base-class part that must be initialised. C++ handles this by calling the base constructor first, automatically.
When the base constructor needs arguments, the derived constructor passes them using an initialization list, which is also the only way to initialise const and reference members. This lesson covers both, and the exact order in which constructors and destructors run.
1. Order of Constructor and Destructor Calls
When a derived object is created:
- the base class constructor runs first,
- then the derived class constructor.
When it is destroyed, the order is reversed: derived destructor first, then base. The base part must exist before the derived part is built on top of it, and must outlive it.
| Inheritance | Constructors run | Destructors run |
|---|---|---|
Single: B → D | B, then D | D, then B |
Multilevel: A → B → C | A, B, C | C, B, A |
Multiple: class D : public B1, public B2 | B1, B2 (order of declaration in the class header), then D | D, B2, B1 |
| With a virtual base class | virtual bases first, then the others | reverse |
#include <iostream>
using namespace std;
class A {
public:
A() {
cout << "A constructor" << endl;
}
~A() {
cout << "A destructor" << endl;
}
};
class B : public A {
public:
B() {
cout << "B constructor" << endl;
}
~B() {
cout << "B destructor" << endl;
}
};
class C : public B {
public:
C() {
cout << "C constructor" << endl;
}
~C() {
cout << "C destructor" << endl;
}
};
class X {
public:
X() {
cout << "X constructor" << endl;
}
~X() {
cout << "X destructor" << endl;
}
};
class Y {
public:
Y() {
cout << "Y constructor" << endl;
}
~Y() {
cout << "Y destructor" << endl;
}
};
class Z : public Y, public X { // Y is listed first, so Y is built first
public:
Z() {
cout << "Z constructor" << endl;
}
~Z() {
cout << "Z destructor" << endl;
}
};
int main() {
cout << "-- multilevel A -> B -> C --" << endl;
{ C c; }
cout << "-- multiple Z : Y, X --" << endl;
{ Z z; }
return 0;
}Output:
-- multilevel A -> B -> C --
A constructor
B constructor
C constructor
C destructor
B destructor
A destructor
-- multiple Z : Y, X --
Y constructor
X constructor
Z constructor
Z destructor
X destructor
Y destructor2. Passing Arguments to Base Class Constructors
If the base class has only parameterized constructors, the derived class must have a constructor that passes the arguments. The base constructor is named in the derived constructor's initialization list, after a colon:
The derived constructor receives all the values: some it uses itself, the rest it passes on to the base.
#include <iostream>
using namespace std;
class Alpha {
int x;
public:
Alpha(int i) {
x = i;
cout << "alpha initialized" << endl;
}
void showX() {
cout << "x = " << x << endl;
}
};
class Beta {
float y;
public:
Beta(float j) {
y = j;
cout << "beta initialized" << endl;
}
void showY() {
cout << "y = " << y << endl;
}
};
class Gamma : public Beta, public Alpha { // Beta is declared first
int m, n;
public:
Gamma(int a, float b, int c, int d) : Beta(b), Alpha(a) { // arguments passed to both bases
m = c;
n = d;
cout << "gamma initialized" << endl;
}
void showMN() {
cout << "m = " << m << ", n = " << n << endl;
}
};
int main() {
Gamma g(5, 10.75, 20, 30);
g.showX();
g.showY();
g.showMN();
return 0;
}Output:
beta initialized
alpha initialized
gamma initialized
x = 5
y = 10.75
m = 20, n = 30Beta is constructed first because the class header lists Beta first. The order of declaration in the class header decides, not the order in the initialization list: writing : Alpha(a), Beta(b) would still construct Beta first (GCC warns about the mismatch with -Wreorder), so it is good practice to write the list in declaration order, as here.
Multilevel: each class passes on to its direct base
#include <iostream>
using namespace std;
class Person {
protected:
char name[20];
public:
Person(const char* n) {
int i = 0;
while (n[i] != '\0' && i < 19) {
name[i] = n[i];
i++;
}
name[i] = '\0';
}
};
class Employee : public Person {
protected:
int id;
public:
Employee(const char* n, int i) : Person(n) {
id = i;
}
};
class Manager : public Employee {
int teamSize;
public:
Manager(const char* n, int i, int t) : Employee(n, i) {
teamSize = t;
}
void show() {
cout << name << " (ID " << id << ") manages " << teamSize << " people" << endl;
}
};
int main() {
Manager m("Kavya", 7001, 12);
m.show();
return 0;
}Output:
Kavya (ID 7001) manages 12 peopleManager passes to Employee, which passes to Person. A class passes arguments only to its direct base (the exception is a virtual base class, which the most derived class initialises; Lesson 30).
3. The Initialization List
The initialization list is not only for base classes. Data members can also be initialised in it:
class Point {
int x, y;
public:
Point(int a, int b) : x(a), y(b) {} // initialization list
};Initialization vs assignment
In the initialization list : x(a) | In the constructor body { x = a; } |
|---|---|
| the member is created with its value | the member is first created (default value or garbage), then assigned |
| one step | two steps (slower for class-type members) |
works for const and reference members | cannot set const or reference members |
| works for members whose class has no default constructor | needs a default constructor for class-type members |
When the initialization list is compulsory
constdata members: they cannot be assigned, only initialised.- Reference members: a reference must be bound when it is created.
- Member objects of a class with no default constructor.
- Base classes with no default constructor.
#include <iostream>
using namespace std;
class Date {
int d, m, y;
public:
Date(int dd, int mm, int yy) : d(dd), m(mm), y(yy) {} // no default constructor
void show() const {
cout << d << "/" << m << "/" << y;
}
};
class Student {
const int roll; // const member
int& marksRef; // reference member
Date dob; // member object without a default constructor
public:
Student(int r, int& marks, int dd, int mm, int yy)
: roll(r), marksRef(marks), dob(dd, mm, yy) {} // all compulsory here
void show() const {
cout << "Roll " << roll << ", marks " << marksRef << ", born ";
dob.show();
cout << endl;
}
};
int main() {
int marks = 88;
Student s(42, marks, 14, 8, 2005);
s.show();
marks = 91; // s refers to this variable through marksRef
s.show();
return 0;
}Output:
Roll 42, marks 88, born 14/8/2005
Roll 42, marks 91, born 14/8/2005Order of initialization
Members are initialised in the order in which they are declared in the class, not the order in the initialization list. Writing the list in a different order is legal but misleading, and can be a bug when one member is initialised from another:
#include <iostream>
using namespace std;
class Pair {
int first; // declared first: initialised first
int second;
public:
Pair(int v) : first(v), second(first * 2) {} // correct: first is ready
void show() {
cout << first << " " << second << endl;
}
};
int main() {
Pair p(5);
p.show();
return 0;
}Output:
5 10Had second been declared before first, second(first * 2) would use first before it was initialised. GCC warns about this with -Wreorder.
Key points to remember
- Base constructors run before derived ones; destructors run in reverse.
- In multiple inheritance, bases are constructed in the order they are declared in the class header.
- Pass arguments to a base with
Derived(...) : Base(...) { }; a class initialises only its direct bases (except virtual bases). - The initialization list is compulsory for
constmembers, reference members, and members or bases with no default constructor. - Members are initialised in declaration order, whatever the order in the list.
📝 IPU End-Term Exam Corner (5-10 Marks)
- Q1. Explain the order of execution of constructors and destructors in multilevel and multiple inheritance with a program. (10 Marks)
- Write: the table and the
A/B/CandZ : Y, Xprogram with its output. - Q2. How are arguments passed to base class constructors? Write a program with multiple inheritance. (5 Marks)
- Write: the syntax and the
Alpha/Beta/Gammaprogram; point out whybetais initialised first. - Q3. What is an initialization list? When must it be used? (5 Marks)
- Write: the syntax, the initialization vs assignment table, the four compulsory cases, and the
Studentprogram. - Q4. In what order are data members initialised? (2.5 Marks)