Class Inheritance

 

As mentioned earlier, inheritance is handy in understanding the role of the 'protected' access specifier. It is possible to inherit attributes and methods from one class to another.

 

There are two important terms for it's description:

 

Derived class : Inherited from another class

Base class: Class being inherited from

 

This can be understood better from the parent child analogy. Parents are the ones passing on their characteristics to us and we inherit them. Hence Derived class is the child and Base class the parent.

 

We use the colon (:) symbol to inherit from a class

 

Example:

 

#include <iostream>
#include <string>

using namespace std;

// Base class
class Food
{
public:
  string brand = "Dominos";
  void ready ()
  {
    cout << "Pizza is ready! \n";
  }
};

// Derived class
class Junk_food:public Food
{
public:
  string place = "4D square";
};


int main ()
{
  Junk_food my_food;
  my_food.ready ();
  cout << my_food.brand + " " + my_food.place;
  return 0;

}

 

Output:

Pizza is ready!
Dominos 4D square

 

Multi-level Inheritance:

 

A class can also be derived from a class, which is already derived from another class.

 

Example

 

#include <iostream>

using namespace std;

// Base class
class My_mom
{
public:
  void my_Function ()
  {
    cout << "Mother";
  }
};


// Derived class
class Me:public My_mom
{
};

// My child
class MyChild:public Me
{
};

int main ()
{
  MyChild myObj;
  myObj.my_Function ();

  return 0;


 

Output:

Mother

 

Multiple Inheritance

 

Class derived from multiple base class, using a comma separated list

 

Example:

#include <iostream>
using namespace std;

// Base class
class MyClass
{
public:
  void myFunction ()
  {
    cout << "Base Class 1\n";
  }
};


// Another base class
class MyOtherClass
{
public:
  void myOtherFunction ()
  {
    cout << "Base Class 2\n";
  }
};

// Derived class
class MyChildClass:public MyClass, public MyOtherClass
{
};

int main ()
{
  MyChildClass myObj;
  myObj.myFunction ();
  myObj.myOtherFunction ();

  return 0;

 

Output:

Base Class 1
Base Class 2