Programming with Passion

Make the best out of everything.

Saturday, 26 March 2016

Concept of Inheritance in OOP

Inheritance is one of the key feature of object-oriented programming including C++ which allows user to create a new class(derived class) from a existing class(base class).  The derived class inherits all feature from a base class and it can have additional features of its own.
Inheritance feature in object oriented programming including C++.

Concept of Inheritance in OOP

Suppose, you want to calculate either area, perimeter or diagonal length of a rectangle by taking data(length and breadth) from user. You can create three different objects(AreaPerimeter and Diagonal) and asks user to enter length and breadth in each object and calculate corresponding data. But, the better approach would be to create a additional object Rectangle to store value of length and breadth from user and derive objects AreaPerimeter and Diagonal from Rectangle base class. It is because, all three objects AreaPerimeter and diagonal are related to object Rectangle and you don't need to ask user the input data from these three derived objects as this feature is included in base class.
Visualization of a program using inheritance feature in C++ Programming

Implementation of Inheritance in C++ Programming

class Rectangle 
{
  ... .. ...
};

class Area : public Rectangle 
{
  ... .. ...
};

class Perimeter : public Rectangle
{
  .... .. ...
};
In the above example, class Rectangle is a base class and classes Area and Perimeterare the derived from Rectangle. The derived class appears with the declaration of class followed by a colon, the keyword public and the name of base class from which it is derived.
Since, Area and Perimeter are derived from Rectangle, all data member and member function of base class Rectangle can be accessible from derived class.
Note: Keywords private and protected can be used in place of public while defining derived class(will be discussed later).

No comments:

Post a Comment