C++ Inheritance

C++ Inheritance is used to create a new inherited class from the reuse of the existing class. The new class inherits all the properties and behavior of the existing class. It is the best example of an object-oriented concept in C++.

cpp inheritance

In inheritance, the existing class is known as the parent class or base class and the new class is known as the child class or derived class.


Example 1:

Suppose we have a parent class “vehicle” with functions condition (), milageCovered (), and fuelCapacity (). We have another class “car” known as the child class of “vehicle”. In inheritance, it shares all the functions in the “vehicle” class and may have its own new functions.


Advantages of using C++ inheritance

  • Reusability: Inheritance allows the user to reuse code again and again in other applications.
  • Time efficient: It saves a lot of time to write the same classes again.
  • Reliability: The use of an already compiled class enhances the reliability of the program.
  • Structure: It enhances the readability and understanding of the program code.

 Example 2: C++ Inheritance

//Inheritance in C++
#include <iostream>
#include <string>
using namespace std;

// parent class
class Vehicle {
  public: 
    
     void condition() {
      cout << "Brand New \n" ;
    }
     void milageCovered()
    {
    	cout << "Zero" ;
	}
     void fuelCapacity()
    {
    		cout << "45 Ltr" ;
	}
};

// child class
class Car: public Vehicle {
  public: 
    void carType()
    {
    	cout << "Car" ;	
	}
};
//main function
int main() {
  Car carDetails;
  carDetails.condition();
  carDetails.carType();
    return 0;
}

Output

Brand New
Car

Recommended Articles

C++ student grade program

C++ File Handling