Friday, September 19, 2008

Inheritance in C++

Inheritance

It is a mechanism to reuse and extend existing classes.

Creating and deriving a class from existing class is also known as inheritance in C++.

New Created class is called
Derived Class and extended class (old class) is called Base class.

Derived class can have all the features of base class and we can add new features to derived class.

Adding new features in base class to make derived class is called extension of base class.

In general we can formulate it-

Base Class + New features = Derived Class

Example :
We can create a base class named fruit and define derived classes as , mango, apple, banana Each of these derived classes has all the features of the base class (fruit) with extra attributes or features specific to these derived classes. Mango would have its own defined features, apple would have its own defined features, banana would have its own defined features, etc.

C++ inheritance is similar to a parent-child relationship. According to inheritance concept, When a class is inherited all the functions and data member are inherited. In C++, every thing from the base class can not be inherited. Yes! we are talking about some exceptional cases. Just have a look-

We can't inherit->
  • The constructor and destructor of a base class
  • The assignment operator
  • The friend functions and friend classes of the base class
(Don't worry .. Very soon we will learn about friends..
Yes friends are also there in C++. They will become your fast friend in certain cases.)