Skip to main content
Brave Programmer Logo

BraveProgrammer

BraveProgrammer

HomeProjectsBlogsCoursesLessonsAbout

Site footer

BraveProgrammer

Free coding courses, practical tutorials, and real projects from BraveProgrammer. Learn web development with React, Next.js, and TypeScript.

Navigation

  • Home
  • Projects
  • Blogs
  • Courses

Resources

  • About
  • Lessons
  • Teach on BraveProgrammer

© 2026 BraveProgrammer. All rights reserved.

Lesson 22: Inheritance | C++ Course lesson | BraveProgrammer
  1. Courses
  2. /
  3. C++ Course

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.

4 points
  • Public, protected, and private inheritance
  • Base‑class constructor invocation
  • Object slicing pitfalls
  • When to favor composition over inheritance

Inheritance

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.


Example: Simple Shape hierarchy

class 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.

Make it stickPractice what you've learned1 quiz · 2 practical tests · Optional activities from C++ CourseBrowse activities
Previous lessonLesson 21: Operator OverloadingContinue to lesson 23Lesson 23: Polymorphism and Virtual FunctionsBack to C++ Course curriculum