Single Inheritance
Single Inheritance
Single inheritance is defined as the inheritance in which a derived class is inherited from the only one base class.
C++ Single Level Inheritance Example: Inheriting Fields
When one class inherits another class, it is known as single level inheritance. Let's see the example of single level inheritance which inherits the fields only.
#include <iostream>
using namespace std;
class Account
{
public:
float salary = 60000;
};
class Programmer: public Account
{
public:
float bonus = 5000;
};
int main(void)
{
Programmer p1;
cout<<"Salary: "<<p1.salary<<endl;
cout<<"Bonus: "<<p1.bonus<<endl;
return 0;
}
In the above example, Employee is the base class and Programmer is the derived class.
C++ Single Level Inheritance Example: Inheriting Methods
Let's see another example of inheritance in C++ which inherits methods only.
#include <iostream>
using namespace std;
class Animal
{
public:
void eat() {
cout<<"Eating..."<<endl;
}
};
class Dog: public Animal
{
public:
void bark()
{
cout<<"Barking...";
}
};
int main(void)
{
Dog d1;
d1.eat();
d1.bark();
return 0;
}