Lesson 15 of 45 · C++
Lesson 22: Inheritance
Duration: 11 min
Lesson 15 of 45 · C++
Duration: 11 min
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.