Single Inheritance In C++

The inheritance in which a derived class is inherited from only one base class is known as single inheritance. The single inheritance in c++ is simple and very easy to understand.

Single Inheritance in c++
Single Inheritance In C++

Where ‘A’ is the base class, and ‘B’ is the derived class.

Single Level Inheritance Example In C++ By Inheriting Fields

Single level inheritance occurs when one class inherits from another. Consider the case of single-level inheritance, which simply inherits fields.

#include <iostream>  
using namespace std;  
 class Account 
 {  
   public:  
   float salary = 70000;   
 };  
 class Programmer: public Account
 {  
   public:  
   float bonus = 6000;    
 };       
int main(void) 
{  
     Programmer p1;  
     cout<<"Salary: "<<p1.salary<<endl;    
     cout<<"Bonus: "<<p1.bonus<<endl;    
    return 0;  
}  

Output:

Salary: 70000
Bonus: 6000

The Employee is the base class in this example, while the Programmer is the derived class.

Join Our Community To Know More

Join our WhatsApp Group To know more About Programming Language tips, tricks and knowledge about programming and how to start learning any programming language.

Single Level Inheritance Example In C++: Inheriting Methods

Let’s look at another C++ inheritance example where just methods are passed down.

#include <iostream>  
using namespace std;  
 class Animal {  
   public:  
 void eat() {   
    cout<<"The Dog is Eating."<<endl;   
 }    
   };  
   class Dog: public Animal    
   {    
       public:  
     void bark(){  
    cout<<"The Dog is Barking.";   
     }    
   };   
int main(void) {  
    Dog d1;  
    d1.eat();  
    d1.bark();  
    return 0;  
} 

Output:

The Dog is Eating.
The Dog is Barking.
Default image
Lingaraj Senapati
Hey There! I am Lingaraj Senapati, the Co-founder of lingarajtechhub.com My skills are Freelance, Web Developer & Designer, Corporate Trainer, Digital Marketer & Youtuber.
Articles: 217

Newsletter Updates

Enter your email address below to subscribe to our newsletter

Leave a Reply