C++ Inheritance

Inheritance in c++ 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++.

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 having functions condition (), milageCovered (), and fuelCapacity (). We have another class “car” known as the child class of vehicles. In inheritance, it shares all the functions in the vehicle class and may have its own few functions.


Advantages of using inheritance

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

 Example 2: Inheritance in c++

//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

Leave a Reply