Oops! It appears that you have disabled your Javascript. In order for you to see this page as it is meant to appear, we ask that you please re-enable your Javascript!

Inheritance in CPP (C plus plus)

Inheritance in CPP (C Plus Plus)

Today, in this fresh and new article, we will cover the following topics;

  1. What is inheritance?
  2. Program of inheritance in C Plus Plus

What is inheritance?

Inheritance is an object-oriented technique in which we can create a new derived class from an existing base class. We can say that base class is the parent class and derived class is the child class.

The child class inherits all the features from the parent class and child class can also have some additional features of its own.

Program on inheritance in C++ (OOP )

#include <iostream>

using namespace std;

class person
{
     public:
         int age;
         string profession;

        person(): profession("Unemployed"), age(14) { }
        
        void show()
        {
             cout << "My Profession is: " << profession <<endl;
             cout << "My Age is: " << age <<endl;
             w();
             t();
        }
        
        void w() { cout << "I can walk." <<endl ;}
        void t() { cout << "I can talk." <<endl ;}
};

class mathteacher : public person
{
    public:
       void teachmath()
	    {
		cout << "I can teach Mathematics." <<endl<< endl;
	      }
};

class footballer : public person
{
    public:
       void play_football() { cout << "I can play Football." << endl; }
};

int main()
{
     mathteacher teacher;
     teacher.profession = "Teacher";
     teacher.age = 23;
     teacher.show();
     teacher.teachmath();

     footballer footballer;
     footballer.profession = "Footballer";
     footballer.age = 19;
     footballer.show();
     footballer.play_football();

     return 0;
}

Output:

Inheritance in CPP (C plus plus)

Figure: Inheritance in CPP (C plus plus)

Topic Covered

Inheritance in CPP (C plus plus).