Lesson 14 of 19
Inheritance
Inheritance
Inheritance lets a class (derived class) reuse and extend the behavior of another class (base class). It models an "is-a" relationship.
Syntax
class Animal {
public:
string name;
Animal(string n) : name(n) {}
void breathe() {
cout << name << " breathes" << endl;
}
};
class Dog : public Animal {
public:
Dog(string n) : Animal(n) {} // call base constructor
void bark() {
cout << name << " barks: Woof!" << endl;
}
};
Dog inherits name and breathe() from Animal, and adds bark().
Dog d("Rex");
d.breathe(); // Rex breathes
d.bark(); // Rex barks: Woof!
Calling the Base Constructor
The derived class constructor must call the base constructor in the initializer list:
class Cat : public Animal {
public:
Cat(string n) : Animal(n) {} // passes n to Animal's constructor
};
Overriding Methods
A derived class can provide its own version of an inherited method:
class Animal {
public:
void speak() {
cout << "..." << endl;
}
};
class Dog : public Animal {
public:
void speak() { // hides Animal::speak
cout << "Woof!" << endl;
}
};
Multiple Levels
Inheritance can be chained:
class LivingThing { ... };
class Animal : public LivingThing { ... };
class Dog : public Animal { ... };
Dog inherits from both Animal and LivingThing.
Access Control in Inheritance
With public inheritance:
publicmembers of the base remainpublicprivatemembers of the base are inaccessible in derived- Use
protectedfor members that derived classes can access but outsiders cannot
Your Task
Create:
- An
Animalbase class with anameand abreathe()method - A
Dogclass that inherits Animal and addsbark() - A
Catclass that inherits Animal and addsmeow()
Create one dog and one cat, call their methods.
JSCPP loading...
Loading...
Click "Run" to execute your code.