• Home
  • How Does Single Inheritance Work in C++?

How Does Single Inheritance Work in C++?

In single inheritance, a class is derived from a single base class. The derived class inherits the data members and member functions of the base class and can also have its own data members and member functions. This allows the derived class to reuse the code in the base class and also extend it by adding its own code.

Here is an example of single inheritance in C++:

// Base class
class Shape {
protected:
int width, 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; }
};

In this example, the Rectangle class is derived from the Shape class and inherits its data members width and height. It also has its own member function getArea() which calculates the area of the rectangle using the inherited width and height values.