HOME C C++ PYTHON JAVA HTML CSS JAVASCRIPT BOOTSTRAP JQUERY REACT PHP SQL AJAX JSON DATA SCIENCE AI

C++ Inheritance

Definition:

The capability of a class to derive properties and characteristics from another class is called Inheritance.Inheritance is one of the most important features of Object-Oriented Programming.Inheritance is a feature or a process in which, new classes are created from the existing classes. The new class created is called “derived class” or “child class” and the existing class is known as the “base class” or “parent class”. The derived class now is said to be inherited from the base class.


Need of Inheritance


Inheritance is an important feature of object oriented programming used for code reusability. It is a process of creating new classes called derived classes, from the existing or base classes. Inheritance allows us to inherit all the code (except declared as private) of one class to another class. The class to be inherited is called base class or parent class and the class which inherits the other class is called derived class or child class.The derived class is a power packed class, as it can add additional attributes and methods and thus enhance its functionality.


Example:


    // Example: define member function without argument within
// the class

#include <iostream>
using namespace std;

class Person {
	int id;
	char name[100];

public:
	void set_p()
	{
		cout << "Enter the Id:";
		cin >> id;
		cout << "Enter the Name:";
		cin >> name;
	}

	void display_p()
	{
		cout << endl <<"Id: "<< id << "\nName: " << name <> course;
		cout << "Enter the Course Fee:";
		cin >> fee;
	}

	void display_s()
	{
		display_p();
		cout <<"Course: "<< course << "\nFee: " << fee << endl;
	}
};

int main()
{
	Student s;
	s.set_s();
	s.display_s();
	return 0;
}

   

Output



Types of Inheritance


Modes of Inheritance


The below table summarizes the above three modes and shows the access specifier of the members of the base class in the subclass when derived in public, protected and private modes: