Inheritance helps for code reusability. Member functions and data members can be inherited to another class. The class to which the properties are inherited is called derived class. The class from which the properties are inherited is called the base class.
The following program shows inheritance. Class ‘breakfast‘ inherits data member from the class ‘eatables‘. Here, class eatables is the base class and the class breakfast is the derived class.
#include<iostream>
using namespace std;
class eatables {
public:
string fruits;
};
class breakfast: public eatables {
public:
string juice;
};
int main () {
breakfast obj1;
obj1.fruits = "apple";
obj1.juice = "orange";
cout<<"The breakfast is of "<<obj1.fruits<<" fruit and "<<obj1.juice<<" juice"<<endl;
return 0;
}
Output:
The breakfast is of apple fruit and orange juice
A class can be derived from a derived class which is already derived from a base class. This type of inheritance is called the multilevel inheritance.
The following program shows multilevel inheritance. The class ‘breakfast‘ inherits properties from class ‘drinks‘. Class drinks inherits properties from the class eatables.
#include<iostream>
using namespace std;
class eatables {
public:
string fruits;
};
class drinks : public eatables {
public:
string juice;
};
class breakfast: public drinks {
public:
string item;
};
int main() {
breakfast obj1;
obj1.fruits = "apple";
obj1.juice = "orange";
obj1.item = "milk";
cout<<"The breakfast is of "<<obj1.fruits<<" fruit, "<<obj1.juice<<" juice"<< " and "<<obj1.item<<"shake"<<endl;
return 0;
}
Output:
The breakfast is of apple fruit, orange juice and milkshake
A class can be derived from more than one classes. This type of inheritance is called multiple inheritance.
The following program shows the multiple inheritance. Class ‘breakfast‘ is derived from classes ‘eatables‘ and ‘drinks‘.
#include<iostream>
using namespace std;
class eatables {
public:
string fruits;
};
class drinks {
public:
string juice;
};
class breakfast: public eatables, public drinks {
public:
string item;
};
int main() {
breakfast obj1;
obj1.fruits = "apple";
obj1.juice = "orange";
obj1.item = "milk";
cout<<"The breakfast is of "<<obj1.fruits<<" fruit, "<<obj1.juice<<" juice"<< " and "<<obj1.item<<"shake"<<endl;
return 0;
}
Output:
The breakfast is of apple fruit, orange juice and milkshake