C++ Inheritance

It is possible for classes in C++ to inherit methods and attributes from one another.

It aids in the reuse of code. When you create a new class, you may reuse the characteristics and methods of an existing class.

The "inheritance idea" is divided into two categories. Base class (parent) is the class being inherited from, whereas Derived class (child) is the class that inherits from another class.

Code:



  #include 
  #include "string"
  using namespace std;

  // Base class
  class Vehicle {

    public:

      string brand = "General Motors";
      void beep() {
      cout << "Tuut, tuut \n" ;
  }
  };

  // Derived class
  class Car: public Vehicle {

    public:
      string model = "Cadillac";
  };

  int main() {

    Car myCar;
    myCar.beep();

    cout << myCar.brand + ", " + myCar.model;
    return 0;
  }
            

Output:


Tuut, tuut
General Motors, Cadillac

In the code, the child class “Car” inherits the attributes and methods from the parent class Vehicle.And additionally , it we can define the Child class own Members.






© Copyright 2022 Advanced PLC. All rights reserved.