Base constructor
- C++ course
- Intermediate
- Lesson 16/116
- 5 min
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() { }.
Practice 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.
Starter code
#include <iostream>
#include <string>
// Define Animal and Dog classes here
int main() {
// Create a Dog instance and print name
return 0;
}Sample 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;
}Expected output
Rex
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 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 Correct answer
- Creates an Animal member
- Destroys Animal
Explanation: Animal(n) calls the base class constructor with n.
2 Complete the base constructor call
Dog(std::string n) : ____(n) { }
Dog(std::string n) : Animal(n) { }
Explanation: Animal(n) calls the base class constructor.
3 Match each stage to its order
| Term | Meaning |
|---|---|
Animal(n) |
First constructor to run |
Dog body |
Second part to run |
~Dog() |
First destructor to run |
~Animal() |
Second destructor to run |