Inheritance basics
- C++ course
- Intermediate
- Lesson 13/116
- 5 min
Learn to inherit from a base class with the : operator.
Inheritance basics
In C++, inheritance lets a class take over the members of another class. The class that inherits is the derived class; the class inherited from is the base class. It is written with a colon and an access modifier.
Example: class Dog : public Animal { };. Here Dog inherits from Animal. Dog has all public members of Animal and can add its own. This reduces code duplication: shared behavior is written once in Animal and inherited by classes like Dog and Cat.
Inheriting members
The derived class inherits the public and protected members of the base class. private members are not inherited; only the base class itself can access them. The derived class can reach them indirectly through the base class's member functions.
Example: if Animal has protected: std::string name;, Dog can use it directly: name = "Rex";. But if it were private, Dog could not access it; Animal would need a getName() function. That is why protected is common for inheritance.
Practice Derive Dog from Animal
Define an Animal class: under public: the member function void breathe() { std::cout << "Breath"; }. Then derive Dog with class Dog : public Animal { };. In main create Dog d; and call d.breathe().
Starter code
#include <iostream>
// Define Animal class and Dog derivation here
int main() {
// Create a Dog instance and call breathe
return 0;
}Sample solution
#include <iostream>
class Animal {
public:
void breathe() {
std::cout << "Breath";
}
};
class Dog : public Animal {
};
int main() {
Dog d;
d.breathe();
return 0;
}Expected output
Breath
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 In class Dog : public Animal { };, what is Animal?
class Dog : public Animal { };- A member variable of Dog
- A constructor of Dog
- The base class of Dog Correct answer
- A friend class of Dog
Explanation: Animal is the base class that Dog inherits from.
2 Complete the inheritance syntax
class Dog ____ public Animal { };
class Dog : public Animal { };
Explanation: The colon starts the inheritance relationship.
3 Match each term to its role
| Term | Meaning |
|---|---|
Animal |
Base class |
Dog |
Derived class |
public |
Inheritance access type |
: |
Inheritance relation |