C++ : Inheritance : Types, Single Inheritance

Inheritance :


- Inheritance is the process of copying characteristics of one class into another class

- Minimum two class are required 1. Base class 2. Derived class

- Only public & protected members will get inherited

- Private members of a class will never get inherited

- To do inheritance while defining derived class use : (colon) operator      to indicate inheritance

- This feature supports re-usability where use existing class and add    some features to create a new class

- This avoids a burden of writing a class again and also saves memory



Type of Inheritance

--------------------------

- Single Inheritance 

- Multiple Inheritance

- Multilevel Inheritance

- Hybrid Inheritance

- Hierarchical Inheritance


Single Inheritance :

This inheritance contains one BASE class and one DERIVED class.


Student

 |

  Test


in above, Student is a base class and Test is derived class. Test is inheriting Student class because of this all public & protected members of class will be inherited into Test class. Using derived class Test object one can access both BASE class and DERIVED class.


For Example:


#include<iostream>

class Student //BASE class

{

  private:

int rno;

  public:

void readstudent(int);

void printstudent(void);

};


void Student::readstudent(int r)

{

rno=r;

}


void Student :: printstudent(void)

{

cout<<"\nRno="<<rno;

}


class Test : Student //Test is derived class, : colon indicate inheritance

{

   private: 

          int subject1, subject2;


   public:

void readtest(int,int);

void printtest(void);

};


void Test:: readtest(int x,int y)

{

 subject1=x;

 subject2=y;

}

void Test::printtest(void)

{

 cout<<"\nSubject1 = "<<subject1

<<"\nSubject2="<<subject2;

}


main()

{

 Test t1; //Derived class object accessing both class functions

 t1.readstudent(101);

 t1.readtest(80,95);

 t1.printstudent();

 t1.printtest();

}


Comments