C++ Inheritance

October 27, 2015 Posted by WithU Technologies
As we know we humans classify humans on the basis of our language, from where we belong, etc.
·         Such as Chinese, Nigerian, Indian, American all are derived from the base class Humans. But still they are classified on the basis of their place of belonging.

·         Thus even the Chinese people have two eyes, one nose, two ears, one mouth and blood with a colour of red as like others do. 

·         That means they all have something common in between them and which are common to all Human beings. This is known as inheritance where we inherit some quality from our predecessor or parent class.

Inheritance simply means parents to child.
·         So we all inherit many common properties from the human class and thus Human class resemble the base class. Thus the properties which are inherited by other class are called the Base class.

·         And the American, Chinese, Indian all are the derived class. Thus the class which inherits the properties are called the Derived class.

·         Along with all the features derived from the base class it has its own additional features.

Example:

#include<iostream>
using namespace std;

class Humans{

public:

  Humans(){     //Constructor without any parameter

  };

 void HumansHave(){   //function with  void return type

       cout<<"- Two Ears"<<endl;

       cout<<"- Two eyes"<<endl;

       cout<<"- One Nose"<<endl;

       cout<<"- One Mouth"<<endl;

 }

};

class Indians:public Humans {  //new class Indians declared and after that the Base class is specified using a colon and an access specifier public

public:

      Indians(){   //Blank constructor without any parameters

}

};

int main(){  //main function

      Indians result;  //new object result created under Indians class

      result.HumansHave();  //We can call the base class function HumansHave() from Indians class itself as we inherited everything from the base Humans class

}

/*

Output:

- Two Ears

- Two eyes

- One Nose

- One Mouth

 */

·         Thus all public members of Humans class became public members of Indian class.

·         We use a colon just after the declaration of derived class name followed by the access specifier which we use as public and then the base class name (class Indians:public Humans).

·         We can also generated a comma separated list of Base classes as shown here:

      class Indians:public Humans, public Apes, public Mammals

There are few exceptions which cannot be derived from the Base class to the derived class are defined below:

·         Constructors
·         Destructors
·         Overloaded Operators
·         Friend functions