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

© 2026 BraveProgrammer. All rights reserved.

  1. Courses
  2. /
  3. C++ Course

Lesson 15 of 45 · C++

Lesson 22: Inheritance

Duration: 11 min

Inheritance\n\nInheritance 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.\n\n---\n\n## Example: Simple Shape hierarchy\ncpp\nclass Shape {\nprotected:\n std::string name;\npublic:\n explicit Shape(const std::string& n) : name(n) {}\n virtual double area() const = 0; // pure virtual\n virtual ~Shape() = default;\n void print() const { std::cout << name << \" area = \" << area() << '\\n'; }\n};\n\nclass Rectangle : public Shape {\n double width, height;\npublic:\n Rectangle(double w, double h) : Shape(\"Rectangle\"), width(w), height(h) {}\n double area() const override { return width * height; }\n};\n\nclass Circle : public Shape {\n double radius;\npublic:\n Circle(double r) : Shape(\"Circle\"), radius(r) {}\n double area() const override { return 3.14159 * radius * radius; }\n};\n\nint main() {\n Rectangle rect(3, 4);\n Circle circ(2);\n rect.print();\n circ.print();\n return 0;\n}\n\n\nThe override keyword helps catch mismatched signatures at compile time.\n\n> Tip: Prefer public inheritance for an “is‑a” relationship; use protected or private inheritance only for implementation reuse.\n\n---\n\n<Alert type="info">Multiple inheritance should be used sparingly; virtual inheritance can resolve the diamond problem.

Previous: Lesson 21: Operator OverloadingNext: Lesson 23: Polymorphism and Virtual Functions