Inheritance-in-C++ .

In this session i have discussed inheritance in C++ .


A class acquires the properties and behaviours from another class this process is called the inheritance . i.e a child can access all the characterstics from their parents . The main purpose of using inheritance is reusabiliy .

Types of inheritance :

1-Single Inheritance

1-Multilevel Inheritance

1-Multiple Inheritance

1-Hierarchical Inheritance

1-Hybrid Inheritance


Inheritance Syntax :

    class derived-class: access-modifier parent-class
    {
        //body of derived
    }
    

1-Single Inheritance :

CSharp single inheritance image

The class A is the initial class that is used as base for the class B so the A class is called the parent class or base class or super class . The class B is called the derived class or child class or sub class . In my case the B class acquires the Sum() from A class after inheritance . The B class has its own method sub() .

In single inheritance must be only one parent class and one child class . Inheritance use the : for inherit the class

1-Single Inheritance Demo

Example : Write a program that demonstrate the single inheritance in C++

    #include<iostream>
    using namespace std;  
    class A
    {
        public :    
        void sum(int x,int y)
        {
            int result = x + y;
            cout<<"Sum : "<<result;
        }
    };
    class B: public A
    {
        public :
        void sub(int x,int y)
        {
            int result = x - y;
            cout<<"Sub : "<<result;
        }
    };
    int main()
    {
        A obj1;
        obj1.sum(20,10);
        B obj2;
        obj2.sum(20,10);
        obj2.sub(20,10);
        return 0;
    }
    
 OUTPUT : Sum : 30
          Sum : 30
          Sub : 10
 

Welcome to AndroidATPoint.

back image                     next image