Inheritance
The mechanism that
allows us to extend the definition of a class without making any physical
changes to the existing class is called as inheritance. Or in other words by
using inheritance child class can acquire the properties of parent class.
Inheritance lets
you create new classes from existing class. Any new class that you create from
an existing class is called as derived class and existing class is called as
base class.
Above diagram
represents the inheritance relationship. Mother and Father are represented as
base class or super class or parent class and Daughter is represented as sub
class or derived class or child class.
The inheritance
relationship enables a derived class to inherit features from its base class.
Furthermore, the derived class can add new features of its own. Therefore,
rather than creating the new classes completely from the scratch, you can take
the advantage of inheritance and reduce the software complexity.
Types of
Inheritance
Single Inheritance:
It is the inheritance
hierarchy wherein one derived class inherited from one base class.
Multiple Inheritances:
It is the
inheritance hierarchy wherein one derived class inherited from multiple base
class(es).
Hierarchical
Inheritance:
It is the
inheritance hierarchy wherein multiple subclasses inherited from one base
class.
Multilevel
Inheritance:
It is the
inheritance hierarchy wherein subclass acts as a base class for other classes.
Hybrid
Inheritance:
The inheritance
hierarchy that reflects any legal combination of other four types of
inheritance.
Syntax for
Inheritance
- In order to derive a class
from another, we use a colon (:) in the declaration of the derived class
using the following format :
class derived_class : memberAccessSpecifier base_class
{
...
};
{
...
};
- Where derived_class is the
name of the derived class and base_class is the name of the class on which
it is based. The member Access Specifier may be public, protected or
private
Class Shape is a
base class and we have derived Rectangle (Derived class) and Triangle (Derived
class) classes from the base class.
Limitations of
inheritance
- A derived class inherits
every member of a base class except constructor and destructor.
- Private members of base
classes become members of derived class. But they are inaccessible by the
members of derived class
- Though object-oriented
programming is frequently propagandised as an answer for complicated
projects, inappropriate use of inheritance makes a program more
complicated.
- Invoking member functions
using objects create more compiler overheads.
- In class hierarchy various
data elements remain unused; the memory allocated to them is not utilized.
Inheritance
Reviewed by NEERAJ SRIVASTAVA
on
3:55:00 PM
Rating:
No comments: