DEFINITION 9: INHERITANCE - PRATMG/2143-OOP-Tamang GitHub Wiki
Inheritance is a concept that describes a class's capacity to derive features and traits from another class. One of the most crucial aspects of Object Oriented Programming is inheritance.
- Sub Class: The class that inherits properties from another class is called Sub class or Derived Class.
- Super Class:The class whose properties are inherited by sub class is called Base Class or Super class.
Types of Inheritance in C++:
In single inheritance, one sub class is inherited by one base class only.
// C++ program to explain
// Single inheritance
#include <iostream>
using namespace std;
// base class
class Vehicle {
public:
Vehicle()
{
cout << "This is a Vehicle" << endl;
}
};
// sub class derived from a single base classes
class Car: public Vehicle{
};
// main function
int main()
{
// creating object of sub class will
// invoke the constructor of base classes
Car obj;
return 0;
}
Multiple Inheritance is a C++ feature that allows a class to inherit from multiple classes at the same time. i.e. a subclass can be inherited from multiple base classes.
// C++ program to explain
// multiple inheritance
#include <iostream>
using namespace std;
// first base class
class Vehicle {
public:
Vehicle()
{
cout << "This is a Vehicle" << endl;
}
};
// second base class
class FourWheeler {
public:
FourWheeler()
{
cout << "This is a 4 wheeler Vehicle" << endl;
}
};
// sub class derived from two base classes
class Car: public Vehicle, public FourWheeler {
};
// main function
int main()
{
// creating object of sub class will
// invoke the constructor of base classes
Car obj;
return 0;
}
In this type of inheritance, a derived class is created from another derived class.
// C++ program to implement
// Multilevel Inheritance
#include <iostream>
using namespace std;
// base class
class Vehicle
{
public:
Vehicle()
{
cout << "This is a Vehicle" << endl;
}
};
// first sub_class derived from class vehicle
class fourWheeler: public Vehicle
{ public:
fourWheeler()
{
cout<<"Objects with 4 wheels are vehicles"<<endl;
}
};
// sub class derived from the derived base class fourWheeler
class Car: public fourWheeler{
public:
Car()
{
cout<<"Car has 4 Wheels"<<endl;
}
};
// main function
int main()
{
//creating object of sub class will
//invoke the constructor of base classes
Car obj;
return 0;
}
In this type of inheritance, more than one derived class is created from a single base class.
// C++ program to implement
// Hierarchical Inheritance
#include <iostream>
using namespace std;
// base class
class Vehicle
{
public:
Vehicle()
{
cout << "This is a Vehicle" << endl;
}
};
// first sub class
class Car: public Vehicle
{
};
// second sub class
class Bus: public Vehicle
{
};
// main function
int main()
{
// creating object of sub class will
// invoke the constructor of base class
Car obj1;
Bus obj2;
return 0;
}