Single Inheritance in C++

Inheritance in C++ is one of the key features of Object-oriented programming. It allows user to create a new class (derived class) from an existing class(base class). This makes it easier to create and maintain an application. This also provides an opportunity to reuse the code functionality and fast implementation time. An existing class that is “parent” of a new class is called a base class. New class that inherits properties of the base class is called a derived class. The idea of inheritance implements the is a relationship. For example, mammal IS-A animal, dog IS-A mammal hence dog IS-A animal as well and so on.

Single Inheritance in C++

In this type of inheritance one derived class inherits from only one base class. It is the most simplest form of Inheritance. All other types of Inheritance are a combination or derivation of Single inheritance.

single inheritance in c++

Program of Single Inheritance in C++

Run Online

#include <iostream>
using namespace std;
// Base class
class Shape {
protected:
  int width;
  int height;
public:
  void setWidth(int w) {
    width = w;
  }
  void setHeight(int h) {
    height = h;
  }
};

// Derived class
class Rectangle: public Shape {
  public:
  int getArea() { 
    return (width * height); 
  }
};

int main(void) {
  Rectangle Rect;
  Rect.setWidth(5);
  Rect.setHeight(7);
  // Print the area of the object.
  cout << "Total area: " << Rect.getArea() << endl;

  return 0;
}
Output
Total Objects: 1
Total area: 35
Watch it on YouTube

Leave a Reply

Your email address will not be published. Required fields are marked *