Inheritance in C++

  • October 21, 2022
  • C++
Accessing Elements

Inheritance refers to a class’s ability to derive properties and characteristics from another class. One of the most important aspects of Object-Oriented Programming is inheritance. This also allows:

  • Code reusability 
  • Quick implementation time
  • Runtime polymorphism

In inheritance, there are two kinds of classes:

  • A parent class, also known as a base class, is a class whose properties are inherited by a subclass. Fruits, as in the preceding example, is a parent class.
  • A child class, also known as a derived class, is a class that inherits the properties of another class. Banana, mango, and berry are examples of child classes of the Fruits base class.
Basic Syntax of Inheritance:
class  <derived_class_name> : <access-specifier> <base_class_name>
{
        //body
}

When defining a derived class in this manner, the base class must already be defined or declared before the subclass declaration.

The Access Mode specifies how the properties of the base class will be inherited by the derived class, whether they are public, private, or protected.

Example:
#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(void) {
   Rectangle Rect;
 
   Rect.setWidth(5);
   Rect.setHeight(7);

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

   return 0;
}

Here the Shape class is the base class and its derived class is Rectangle.

Output:
Total area: 35
Visibility of Class Members:

The availability of Superclass members in the subclass varies depending on the Access modifier used during inheritance. It can be private, protected, or open to the public as shown in the given table:

Base class member access specifierType of Inheritance
PublicProtectedPrivate
PublicPublicProtectedPrivate
ProtectedProtectedProtectedPrivate
PrivateNot accessible(Hidden)Not accessible(Hidden)Not accessible(Hidden)

Note: also read about Class Members Pointers in C++

Follow Me

If you like my post please follow me to read my latest post on programming and technology.

https://www.instagram.com/coderz.py/

https://www.facebook.com/coderz.py

Leave a Reply

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