Inheritance Programming Exercise 3 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 Programming Exercise 3

Write a class Teacher that contains the attribute teacher name, age and address.
It also contains member function to input and display its attributes. Write another
Writer that contains the attributes writer name, address and number of books written by him.

It also contains member functions to input and display its attributes. Write
a third class Scholar that inherits both Teacher and Writer classes.


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

class Teacher
{
	protected:
		char name[50], address[100];
		int age;
		public:
			void input()
			{
			 cout<<"Enter teacher name:";
			 gets(name);
			 cout<<"Enter teacher age:";
			 cin>>age;
			 cout<<"Enter teacher address:";
			 gets(address);
		    }
		    void show()
		    {
		    	cout<<"Name:"<<name<<endl;
		    	cout<<"Age:"<<age<<endl;
		    	cout<<"Address:"<<address<<endl;
		    }
};
    class Writer
    {
    	protected:
    		char name[50], address[100];
    		int books;
    		public:
    			void input()
    			{
    			cout<<"Enter writer name:";
    			gets(name);
    			cout<<"Enter writer address:";
    			gets(address);
    			cout<<"Enter number of books written:";
    			cin>>books;
    			}
    			void show()
    			{
    			cout<<"Writer name: "<<name<<endl;
    			cout<<"Address: "<<address<<endl;
    			cout<<"Number of books: "<<books<<endl;
    			}
    };
       class Scholar : public Teacher,public Writer
       {
       	public:
       		void input()
       		{
       			Teacher::input();
       			Writer::input();
       		}
       		void show()
       		{
       			Teacher::show();
       			Writer::show();
       		}
       };
         main()
         {
         	Scholar s;
         	s.input();
         	s.show();
         }

Leave a Reply