Lesson 22 of 45
C++Lesson 22: Inheritance
11 min
Course progress49%
What you'll learn
Keep these ideas in mind as you work through the lesson.
Lesson 22 of 45
C++11 min
Keep these ideas in mind as you work through the lesson.
Inheritance lets a derived class reuse and extend the implementation of a base class. C++ supports single and multiple inheritance. Access specifiers (public, protected, private) control the visibility of inherited members.
Shape hierarchyclass Shape {
protected:
std::string name;
public:
explicit Shape(const std::string& n) : name(n) {}
virtual double area() const = 0; // pure virtual
virtual ~Shape() = default;
void print() const { std::cout << name << \" area = \" << area() << '\
'; }
};
class Rectangle : public Shape {
double width, height;
public:
Rectangle(double w, double h) : Shape(\"Rectangle\"), width(w), height(h) {}
double area() const override { return width * height; }
};
class Circle : public Shape {
double radius;
public:
Circle(double r) : Shape(\"Circle\"), radius(r) {}
double area() const override { return 3.14159 * radius * radius; }
};
int main() {
Rectangle rect(3, 4);
Circle circ(2);
rect.print();
circ.print();
return 0;
}
The override keyword helps catch mismatched signatures at compile time.
Tip: Prefer public inheritance for an “is‑a” relationship; use protected or private inheritance only for implementation reuse.
<Alert type="info">Multiple inheritance should be used sparingly; virtual inheritance can resolve the diamond problem.