C++
Base constructor
Learn to call the base constructor in a derived class.
Base constructor
A derived class constructor can call the base class constructor in its initializer list. This is the standard way to initialize the base class's members. After the colon, the base class name is written with parameters in parentheses.
Example: Dog(std::string n) : Animal(n) { }. Here Animal(n) calls Animal's parameterized constructor with n. The base constructor runs first, then the derived class body. When the base members are ready, the derived class can add its own. This order is always the same.
Order of execution
When a derived object is created, the base class constructor runs first, then the derived class constructor. When destroyed, the order is reversed: the derived destructor runs first, then the base destructor. This order is fixed by the C++ standard.
Example: when you write Dog dog("Rex");, Animal("Rex") is called first, then Dog's body. So Dog's body can safely use Animal's members. If the base class has no virtual destructor, destroying through a base pointer does not work correctly; that is why a base class usually gets virtual ~Animal() { }.
Exercise Call the Animal constructor from Dog
Define an Animal class: public: std::string name; Animal(std::string n) : name(n) { }. Derive Dog from Animal and add the constructor Dog(std::string n) : Animal(n) { }. In main create Dog dog("Rex"); and print dog.name with std::cout.
Show example solution
#include <iostream>
#include <string>
class Animal {
public:
std::string name;
Animal(std::string n) : name(n) {
}
};
class Dog : public Animal {
public:
Dog(std::string n) : Animal(n) {
}
};
int main() {
Dog dog("Rex");
std::cout << dog.name;
return 0;
}
Test yourself
-
In Dog(std::string n) : Animal(n) { }, what does Animal(n) do?
Dog(std::string n) : Animal(n) { }
- Redefines the Animal class
- Calls the Animal constructor with n
- Creates an Animal member
- Destroys Animal
Show answer
Calls the Animal constructor with n — Animal(n) calls the base class constructor with n.
-
Complete the base constructor call
Dog(std::string n) : ____(n) { }
Show answer
Dog(std::string n) : Animal(n) { }
-
Match each stage to its order
- Animal(n)
- First constructor to run
- Dog body
- Second part to run
- ~Dog()
- First destructor to run
- ~Animal()
- Second destructor to run
Next lesson: final