Inheritance
Lesson 14 of 20class Dog : public Animal — children inherit everything the parent has, then add their own twist on top.
Reuse and extend
Inheritance lets a class start from another class: keep what exists, add what is new.
Base class
The parent (Animal) — it holds the members every child should share, like name and eat().
Derived class
class Dog : public Animal — Dog begins with all of Animal’s public members, already written.
The is-a rule
Every Dog is an Animal. Inheritance models "is-a"; a Dog can go anywhere an Animal is expected.
protected:
Members marked protected are visible to child classes but hidden from outside code.
Build a derived class
Four moves turn a base class into a working child — click each stage.
One object, two sources
Press play — eat() arrives from Animal, bark() is Dog’s own. Both run on the same object.
1#include <iostream>2#include <string>34class Animal {5public:6std::string name;7void eat() {8std::cout << name << " eats food\n";9}10};1112class Dog : public Animal {13public:14void bark() {15std::cout << name << " says Woof\n";16}17};1819int main() {20Dog d;21d.name = "Rex";22d.eat();23d.bark();24return 0;25}
The preprocessor pastes in iostream for cout.
Match the inheritance terms
Click a term, then click its description to lock the pair.
Predict the output
A Robot built from a Machine — which calls work, and what prints?
1#include <iostream>2#include <string>3class Machine {4public:5std::string kind;6void start() {7std::cout << kind << " starts\n";8}9};10class Robot : public Machine {11public:12void greet() {13std::cout << kind << " beeps\n";14}15};16int main() {17Robot r;18r.kind = "R2";19r.start();20r.greet();21return 0;22}
Hint: Robot inherits start() from Machine — r.kind works too, because kind is inherited as well.
Key takeaways
class Child : public Parent — the child starts with the parent’s members.
Every derived object is-a base object: Dog is an Animal.
Add new members in the child; inherited ones come for free.
protected: members are visible to child classes, hidden from outsiders.
Reuse beats copy-paste: fix a bug in the base and every child benefits.