11. CPP-Inheritance

CPP Destructors: Previous                                                         Next: CPP Multiple Inheritance

Inheritance is the most common and exciting feature of C++ which provides the reusability. Reusability means to use what we have rather than develop same again (In oops classes are reused).


  • To reuse the existing classes or their features of the class must be extended.
  • The class that is already exists, is known as base class/super class. Or class which taking features of existing class is known as child class/sub class/derived class.
Syntax:
:
{
//members of subclass
};
Note : visibility mode is optional, default is private.
  • When sub class/base class is inheriting the super class with private access modifier then public members of super class will become private members of derived class.
  • When base class is inheriting the super class with public accessible mode then public members of base class will become public that means no change.
  • Private data members are not inherited. They wont go to the derived class.
Types of inheritance :

Single inheritance :
If a class derived from one base class only means only one base class or one child class.
Syntax :
:
{
};
Eg:
#include
#define SIZE 25
class Person
{
private :
char name[SIZE];
int age;
protected:
Person();
void display();
};
Person::person()
{
cout<<”enter name = “;
cin.getline(name,SIZE);
cout<<”enter your age= “;
cin>>age;
}
void Person::display()
{
cout<<”name is= “<
cout<<”age is=”<
}
class student:protected Person
{
int  rollno;
protected:
Student();
void display();
};
Student ::Student()
{
cout<<”enter your rollnumber”;
cin>>rollno;
}
void student ::display()
{
Person::display();
cout<<”roll no is=”<
}
void main()
{
Student std;
std.display();
}
Output:




CPP Destructors: Previous                                                         Next: CPP Multiple Inheritance