Single Inheritance in C++.

C++ Single Inheritance

Single Inheritance: It is the in which a derived class is inherited from the only one base class.

//Let us try to understand with an example.
#include <iostream.h> 
#include <conio.h>
class base    //single base class
{
   public:
     int x;
   void getdata()
   {
     cout << "Enter the value of x = "; cin >> x;
   }
 };
class derive : public base    //single derived class
{
   private:
    int y;
   public:
   void readdata()
   {
     cout << "Enter the value of y = "; cin >> y;
   }
   void product()
   {
     cout << "Product = " << x * y;
   }
 };

 int main()
 {
    derive a;     //object of derived class
    a.getdata();
    a.readdata();
    a.product();
    return 0;
 }       
Expected Output:-

Enter the value of x = 3
Enter the value of y = 4

Product = 12

//Example of inheritance in C++
#include <iostream.h>  
#include <conio.h>
 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;  
}  

Expected Output:-

Salary: 60000
Bonus: 5000
In the above example, Employee is the base class and Programmer is the derived class.

//Example of inheritance in C++ which inherits methods only.

#include <iostream.h>  
#include <conio.h>
 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;  
}  
Expected Output:-

Eating...
Barking...

//Let's see one more simple example.

#include <iostream.h>  
#include <conio.h>
class A  
{  
    int a = 4;  
    int b = 5;  
    public:  
    int mul()  
    {  
        int c = a*b;  
        return c;  
    }     
};  
  
class B : private A  
{  
    public:  
    void display()  
    {  
        int result = mul();  
        std::cout <<"Multiplication of a and b is : "<<result<< std::endl;  
    }  
};  
int main()  
{  
   B b;  
   b.display();  
  
    return 0;  
}  
Expected Output:-


Multiplication of a and b is : 20

#include <stdio.h>
#include <conio.h>
int sum();
void main()
{
int res;
res=sum();
printf("result=%d",res);
getch();
}
sum()
{
int a,b,c;
printf("enter the value of a and b\n");
scanf("%d%d",&a,&b);
c=a+b;
return c;
}

Post a Comment

Previous Post Next Post