This blog is about providing theory as well as simple executable codes of different programming languages such as java, C, C++, and web programming, etc. This blog will be helpful to the IT students to learn about programming.

Wednesday, March 1, 2023

What is inheritance? List different types of Inheritance supported in C++. Write an OOP showing multiple inheritance.

 Inheritance is a mechanism in object-oriented programming where a new class is derived from an existing class. The new class inherits all the properties and behavior of the existing class and can also add its own properties and behavior.

Different types of Inheritance supported in C++ are:

  1. Single Inheritance: A derived class is derived from a single base class.
  2. Multiple Inheritance: A derived class is derived from multiple base classes.
  3. Hierarchical Inheritance: Multiple derived classes are derived from a single base class.
  4. Multilevel Inheritance: A derived class is derived from a base class, which is again derived from another base class.
  5. Hybrid Inheritance: Combination of multiple inheritance and hierarchical inheritance.

Here is an example of multiple inheritance:

#include <iostream>
using namespace std;
// Base class 1
class Shape {
   public:
      void setWidth(int w) {
         width = w;
      }
      void setHeight(int h) {
         height = h;
      }
   protected:
      int width;
      int height;
};
// Base class 2
class PaintCost {
   public:
      int getCost(int area) {
         return area * 70;
      }
};
// Derived class
class Rectangle: public Shape, public PaintCost {
   public:
      int getArea() {
         return (width * height);
      }
};
int main() {
   Rectangle Rect;
   Rect.setWidth(5);
   Rect.setHeight(7);
   int area = Rect.getArea();
   // Print the area of the object.
   cout << "Total area: " << area << endl;
   // Print the total cost of painting
   cout << "Total paint cost: $" << Rect.getCost(area) << endl;
   return 0;
}

In the above example, the Rectangle class is derived from two base classes Shape and PaintCost. The Shape class provides the width and height properties, while the PaintCost class provides the cost calculation method. The Rectangle class inherits both these properties and methods and adds its own method getArea() to calculate the area of the rectangle.

No comments:

Post a Comment

If you have any doubts, please let me know

Slider Widget