C++ Inheritance
Inheritance lets a class (derived/child) reuse and extend the members of another class (base/parent), written as `class Dog : public Animal { ... };`. The derived class automatically gets the base class's public and protected members.
This promotes code reuse: shared behaviour lives in the base class, while each derived class adds or overrides only what makes it different.
Base and derived classes
`class Animal { public: void eat() {...} };` and `class Dog : public Animal { public: void bark() {...} };` โ a Dog object can call both eat() and bark().
Constructors in inheritance
A derived class's constructor can call the base class constructor explicitly using an initialiser list, e.g. `Dog() : Animal() {}`, to pass setup data upward.
class Animal {
public:
void eat() { std::cout << "Eating "; }
};
class Dog : public Animal {
public:
void bark() { std::cout << "Woof"; }
};
int main() {
Dog d;
d.eat();
d.bark();
}Eating WoofDog inherits eat() from Animal and adds its own bark() method.
Key points
- class Derived : public Base establishes inheritance.
- Derived classes gain public/protected members of the base.
- Inheritance promotes code reuse across related classes.
- Derived class constructors can invoke the base constructor.
