C++ - Inheritance -SINGLE INHERITANCE





Inheritance :


The inheritance is the process of creating new classes. The existing class is known as " base class "  and  newly created class is known as derived class. The derived class has all properties of base class.

There are five types of inheritance



1] Single Inheritance.
2] Multiple Inheritance.
3] Multi-Level Inheritance.
4] Hybrid Inheritance.
5] Hierarchical Inheritance.

  Single Inheritance.

        The derived class with only one base class is called as single Inheritance. And derived class has its own property .

Syntax :

class derived_class_name : public base_class_name
{
-          - - - -
-          code
-          ------
-           
};

Note ::  one important thing In Inheritance that is  it is parent child relationship. Child class has property of  Parents class(base class) ,but parent class will not work with child class own property.  

Lets see the code which explain single inheritance.
In below code Property of base class  like    int no, char name[10], void getdata(),  void putdata(), is access by derived class


#include <iostream>
using namespace std;

// base class
class Vehicle {
    int no;
    char name[10];
public:
   
   
        void getdata();
    void putdata();
   
};
class Der: public Vehicle  // here we make the child   class from base class
{
    float basic;
public:
   
        void getdata();
          void putdata();
   
};


void Vehicle::getdata()
{
    cout<<"enter no & name of employe ";
    cin>>no>>name;
}
void Vehicle::putdata()
{
    cout<<no<<"\t"<<name;
}

void Der :: getdata()
{
   
     Vehicle :: getdata();
    cout<<"enter the salary ";
    cin>>basic;
}

void Der :: putdata()
{
     Vehicle::putdata();
    cout<<"\t"<<basic<<endl;
}
int main(int argc, char** argv) {
    Der obj[200];
    int i,n;
    cout<<"enter how many employ ";
    cin>>n;
    for (i=0;i<n;i++)
    {
        obj[i].getdata();
    }
    cout<<"employ no, name ,basic \n";
    for(i=0;i<n;i++)
    {
        obj[i].putdata();
    }
    return 0;
}
******************************
Output
enter how many employ 2
enter no & name of employe 1 A
enter the salary 2000
enter no & name of employe 2 B
enter the salary 305564
employ no, name ,basic
1       A       2000
2       B       305564







Comments