C++ inheritance | AsgarTech

 C++ inheritance | AsgarTech

C++ inheritance is a mechanism by which a new class is created from an existing class, called the base or parent class. In inheritance, the new class inherits the properties and behavior of the base class, and can also add new properties and behavior. This allows for code reuse and enhances the modularity and flexibility of the code.


Here is an example of C++ inheritance:

#include <iostream>

using namespace std;

// Base class

class Shape {

   public:

      void setWidth(int w) {

         width = w;

      }

      void setHeight(int h) {

         height = h;

      }

   protected:

      int width;

      int height;

};

// Derived class

class Rectangle: public Shape {

   public:

      int getArea() {

         return (width * height);

      }

};

int main() {

   Rectangle rect;

   rect.setWidth(5);

   rect.setHeight(7);

   // Print the area of the rectangle

   cout << "Area of rectangle: " << rect.getArea() << endl;

   return 0;

}

here are the types of inheritance in C++


Single Inheritance: In single inheritance, a derived class is derived from only one base class. This is the simplest form of inheritance.

Multiple Inheritance: In multiple inheritance, a derived class is derived from more than one base class. This allows a class to inherit from multiple classes, each providing a different set of functionalities.

Multilevel Inheritance: In multilevel inheritance, a derived class is derived from a base class, which is itself derived from another base class. This allows for the creation of a hierarchy of classes with increasingly specialized functionalities.

Hierarchical Inheritance: In hierarchical inheritance, multiple derived classes are derived from a single base class. This allows for the creation of a group of related classes, each providing a different specialization of the base class.

Hybrid Inheritance: Hybrid inheritance is a combination of two or more types of inheritance. This allows for the creation of complex class hierarchies with a wide range of functionalities.


No comments: