C++ Inheritance
Inheritance is one of the key features of Object-oriented programming in C++.
It allows us to create a new class (derived class) from an existing class (base
class).
The derived class inherits the features from the base class and can have
additional features of its own. For example,
class Animal {
// eat() function
// sleep() function
};
class Dog : public Animal {
// bark() function
};
Here, the Dog class is derived from the Animal class. Since Dog is derived
from Animal , members of Animal are accessible to Dog .
,ELITE TUTORING
Inheritance in C++
Notice the use of the keyword public while inheriting Dog from Animal.
class Dog : public Animal {...};
We can also use the keywords private and protected instead of public . We will
learn about the differences between using private , public and protected later in
this topic.
is-a relationship
Inheritance is an is-a relationship. We use inheritance only if an is-a
relationship is present between the two classes.
Here are some examples:
, ELITE TUTORING
• A car is a vehicle.
• Orange is a fruit.
• A surgeon is a doctor.
• A dog is an animal.
Example 1: Simple Example of C++ Inheritance
// C++ program to demonstrate inheritance
#include <iostream>
using namespace std;
// base class
class Animal {
public:
void eat() {
cout << "I can eat!" << endl;
}
void sleep() {
cout << "I can sleep!" << endl;
}
};
// derived class
class Dog : public Animal {
public:
void bark() {
cout << "I can bark! Woof woof!!" << endl;
}
};
int main() {