C++ Inheritance

C++ Inheritance: Inheritance is the process in which the objects of one class can acquire the properties of another class. And also it supports the concept of hierarchical classification. And also inheritance provides reusability. So, that we can add additional features to the existing class without modifying it.

C++ Inheritance

When creating a class, instead of writing new data members and member functions we can assign that new class which inherits the members of the existing class and the existing class. This is known as the base class and the new class is referred to as the derived class.

Syntax:



class subclass_name : superclass_name
{
// data members
// methods
}

Example:

#include<iostream.h>
#include<conio.h>
class employee
{
public:
int salary;
};
class developer : public employee
{
employee e;
public:
void salary()
{
cout<<"Enter employee salary: ";
cin>>e.salary; //access base class data member
cout<<"Employee salary: "<<e.salary;
}
};

void main()
{
clrscr();
developer obj;
obj.salary();
getch();
}

Output:

Enter employee salary: 50000
Employee salary: 50000

Advantages of Inheritance

The main advantage of Inheritance is code re-usability: Now you can reuse the members of your parent class. So, there is no need to define the member again. So less code is required in the class.

Access Control and Inheritance

A derived class can access all the non-private members of its base class. So the base-class members that should not be accessible to the member functions of derived classes should be declared private in the base class.

Access Public protected private
Same class yes yes yes
Derived classes yes yes no
Outside classes yes no no

A derived class inherits all base class methods with the following exceptions :

  • Constructors, destructors and copy constructors of the base class.
  • Overloaded operators of the base class.
  • The friend functions of the base class.