CPP Single Inheritance

Single Inheritance

  • In this type of inheritance one derived class inherits from only one base class.
  • It is the most simplest form of Inheritance.
  • Single inheritance represents a form of inheritance when there is only one base class and one derived class.

Syntax:

class derived_class_name: visibility_mode base_class_name
{

:::::::::::::: // member of derived class

};

Example:

#include <iostream.h>
// 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); 
      }
};

void main()
{
   Rectangle Rect;
 
   Rect.setWidth(5);
   Rect.setHeight(7);

   // Print the area of the object.
   cout << "Total area: " << Rect.getArea() << endl;

   getch();
}

Output:

Command Prompt
Total area: 35

Share This Page to Download:

Share to Download

Share This Page on:


Ask Question