C++
Summary - Inheritance
Combine virtual/override and final to write a shape hierarchy.
Summary - Inheritance
In this section you learned inheritance and polymorphism. A class inherits from a base class with a colon and public. virtual functions pick the real type when called through a pointer; override marks this explicitly and catches signature mismatches.
A derived constructor calls the base constructor in its initializer list; the base is constructed first, then the derived. final closes class or function inheritance. Now we will bring these together in a task.
Exercise Build a Shape hierarchy
Define a Shape class: under public: virtual int area() { return 0; }. Derive Square from Shape, add an int side; member and the constructor Square(int s) : side(s) { }, and redefine int area() override { return side * side; }. In main create Square sq(5); and print sq.area() with std::cout.
Show example solution
#include <iostream>
class Shape {
public:
virtual int area() {
return 0;
}
};
class Square : public Shape {
public:
int side;
Square(int s) : side(s) {
}
int area() override {
return side * side;
}
};
int main() {
Square sq(5);
std::cout << sq.area();
return 0;
}
Exercise Call the Shape hierarchy polymorphically
Take the Shape and Square definitions above. In main create Square sq(4);, take Shape* p = &sq; and make a polymorphic call with std::cout << p->area(). With virtual, Square::area is called.
Show example solution
#include <iostream>
class Shape {
public:
virtual int area() {
return 0;
}
};
class Square : public Shape {
public:
int side;
Square(int s) : side(s) {
}
int area() override {
return side * side;
}
};
int main() {
Square sq(4);
Shape* p = &sq;
std::cout << p->area();
return 0;
}
What's next?
You learned inheritance and polymorphism: virtual, override, base constructor calls and final. Now it is time to use what you learned in a real project.
In the next section you will build a 5-lesson helper library project. Each lesson adds one piece, and by the final lesson you will have a working module. You will use all your skills: class design, member functions and access modifiers together.
Test yourself
-
What is needed for polymorphism to work?
Animal* a = &dog;
a->speak();
- Only public inheritance
- A private member in the base class
- final in the derived class
- virtual in base class and call via pointer
Show answer
virtual in base class and call via pointer — virtual plus a pointer call enables polymorphism.
-
Write the override keyword
void speak() ____ { std::cout << "Woof"; }
Show answer
void speak() override { std::cout << "Woof"; }
Next lesson: Class design