Inheritance
Okay, let's talk about one of the biggest ideas in Object-Oriented Programming: inheritance. It's one of the four pillars of OOP (alongside encapsulation, polymorphism, and abstraction), and once you get it, a LOT of things in C++ will start to click. The basic idea is simple: you can create a new class (we call it a derived class or child class) that automatically gets all the stuff — variables, functions, everything — from an existing class (the base class or parent class). And then the new class can add its own stuff on top, or even override (replace) the inherited functions with its own versions.
Think of it like biology: a Dog is a type of Animal, right? Every dog has all the properties of an animal (it breathes, it moves, it has a name) PLUS additional properties specific to dogs (it barks, it has a breed). In code, you'd write class Dog : public Animal { ... }; — meaning Dog gets everything from Animal and can add its own features. This is what we call the "is-a" relationship: a Dog IS AN Animal, a Circle IS A Shape, a Manager IS AN Employee.
Let's talk about a few key things you'll pick up this week. Constructor chaining — when you create a Dog object, the Animal constructor runs FIRST, then the Dog constructor. Makes sense, right? You have to build the foundation before you build the house on top of it. Then there's the protected access specifier — it sits between public and private. Protected members are accessible inside the class AND in derived classes, but not from outside code. And finally, the override keyword — it tells the compiler "hey, I'm intentionally replacing this function from the base class." If you accidentally make a typo in the function name, the compiler catches it for you. Pretty handy.
| Access Specifier | Accessible in Class? | Accessible in Derived? | Accessible Outside? |
|---|---|---|---|
public | Yes | Yes | Yes |
protected | Yes | Yes | No |
private | Yes | No | No |
The beauty of inheritance is code reuse — you write the common functionality once in the base class, and every derived class automatically gets it for free. It also sets up a type hierarchy that makes polymorphism possible (that's next week's topic), where you can treat all sorts of different derived objects through a single base class interface.