Thuta Learning
AdvancedProgrammingbeginner

Inheritance

Relax. We'll talk through this in plain words — no textbook voice.

Inheritance is a feature that lets one class inherit the properties and methods of another class. Writing common behavior in a base class and extending it in specific classes cuts down on code duplication.

cpp
#include <iostream>
#include <string>
using namespace std;

class User {
  public:
    string name;

    void login() {
        cout << name << " logged in." << endl;
    }
};

class Admin : public User {
  public:
    void deletePost() {
        cout << name << " deleted a post.";
    }
};

int main() {
    Admin admin;
    admin.name = "Thuta Admin";
    admin.login();
    admin.deletePost();
    return 0;
}

Admin : public User means the Admin class publicly inherits from the User class. That's why an Admin object can use name and login(), while also adding deletePost() on top.

You should see
Thuta Admin logged in. Thuta Admin deleted a post.

Info

Use inheritance when there's a genuine "is-a" relationship. Admin is a User? That fits well. Car has an Engine? Composition is probably a better fit than inheritance there.

Easy traps

  • Don't reach for inheritance just to reuse code. If the relationship isn't a genuine fit, it can end up making your design messier.
Inheritance | Thuta Learning