Inheritance Programming Exercise in C/C++|OOP

What is inheritance?

Inheritance is the most widely used object oriented programming technique. It is used to reuse classes. The word “inherit” means to receive something. Inheritance means some properties that are received from someone or something. For example, we inherit properties from our parents.

Before understanding Inheritance You Should Learn About Functions and Classes.

In inheritance there is a super/parent class “Person”. We have the common properties.

  • Name
  • Age
  • Gender
  • Height

Above are the common properties that every person has. A person may be a

  • Teacher
  • Student
  • Farmer

All have common properties of name, age, gender and height.

So Person is the parent class and the Teacher, Student and Farmer are the sub classes.

Syntax of Parent Class

class Person
{
   protected:
//Member variables
   public:
//Member Functions
};

Syntax of Child Class

class Student : public Person
{
//class definition

};

Inheritance Exercise Question# 1

Write a class Employee that contains attributes of employee id and his scale.
The class contains member function to input and show the attributes.
Write a child class Manager that inherits Employee class.
The child class has attributes of manager id and his department.
It also contains the member functions to input and show its attributes.

#include<iostream>
#include<conio.h>
#include<stdio.h>
using namespace std;

class Employee
{
	protected:
		int eid, scale;
		public:
			Employee()
			{
				eid = -1;
				scale = 0;
			}
			void input()
			{
				cout<<"Enter employee id:";
				cin>>eid;
				cout<<"Enter scale:";
				cin>>scale;
			}
			void show()
			{
			cout<<"Employee ID: "<<eid<<endl;
			cout<<"Scale: "<<scale<<endl;
			}
};
      class Manager : public Employee
	  {
	  	private:
	  		int mid;
	  		char dept[30];
	  		public:
	  			Manager()
	  		      {
	  			    Employee();
	  			    mid = 0;
	  		      }
	  		      void input()
	  		      {
	  		      	Employee::input();
	  		      	cout<<"Enter manager id:";
	  		      	cin>>mid;
	  		      	cout<<"Enter department:";
	  		      	gets(dept);
	  		      }
	  		      void show()
	  		      {
	  		   Employee::show();
	  		   cout<<"Manager ID: "<<mid<<endl;
	  		   cout<<"Department: "<<dept<<endl;
	  		      }
	  };
	       main()
		   {
		   	Manager m;
		   	m.input();
		   	m.show();
		   }     

Leave a Reply