Reusing a class
Cats and dogs are both animals. Every animal has a name and can eat. Instead of writing that code twice, we write it once in an Animal class, and let Dog and Cat inherit it:
#include <iostream>
#include <string>
using namespace std;
class Animal {
public:
string name;
void eat() {
cout << name << " is eating\n";
}
};
class Dog : public Animal { // Dog inherits from Animal
public:
void fetch() {
cout << name << " fetches the ball\n";
}
};
int main() {
Dog d;
d.name = "Rex";
d.eat(); // comes from Animal
d.fetch(); // Dog's own method
return 0;
}Output
Rex is eating Rex fetches the ball
Animalis the base (parent) class.Dogis the derived (child) class. It gets everything public fromAnimal, and adds its own things.: public Animalmeans “a Dog is an Animal”.
Think of it like this: Inheritance is like a family recipe. The child gets the parent's recipe book and can add new recipes of their own.
Calling the parent's constructor
A child class's constructor can pass values up to the parent's constructor in the initializer list:
#include <iostream>
#include <string>
using namespace std;
class Vehicle {
public:
string brand;
int wheels;
Vehicle(string b, int w) : brand(b), wheels(w) {}
void info() const {
cout << brand << " with " << wheels << " wheels\n";
}
};
class Bike : public Vehicle {
public:
bool hasBell;
Bike(string b, bool bell) : Vehicle(b, 2), hasBell(bell) {}
};
int main() {
Bike b("Raleigh", true);
b.info();
cout << "Has a bell: " << b.hasBell << "\n";
return 0;
}Output
Raleigh with 2 wheels Has a bell: 1
protected
private members of the parent are hidden even from its children. If children should be able to use a member but the outside world shouldn't, make it protected:
#include <iostream>
using namespace std;
class Shape {
protected:
int sides;
public:
Shape(int s) : sides(s) {}
};
class Triangle : public Shape {
public:
Triangle() : Shape(3) {}
void describe() const {
cout << "I have " << sides << " sides\n"; // allowed: sides is protected
}
};
int main() {
Triangle t;
t.describe();
return 0;
}Output
I have 3 sides