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

};

Exercise Question 2

Write a class LocalPhone that contains an attribute phone to store a
local telephone number. The class contains member functions to input
and display phone number. Write a child class NatPhone for national
phone numbers that inherits LocPhone class. It additionally contains
an attribute to store city code. It also contains member functions to
input and show the city code. Write another class IntPhone for
international phone numbers that inherits NatPhone class. It additionally
contains an attribute to store country code. It also contains member
functions to input and show the country code.

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

class LocalPhone
{
	protected:
		long ph;
		public:
			void input()
			{
				cout<<"Enter phone no:";
				cin>>ph;
			}
			void show()
			{
			 cout<<ph<<endl;
		    }
};
     class NatPhone : public LocalPhone
     {
     	protected:
     		int ccode;
     		public:
     			void input()
     			{
     				cout<<"Enter city code:";
     				cin>>ccode;
     				LocalPhone::input();
     			}
     			void show()
     			{
     				cout<<ccode<<"";
     				LocalPhone::show();
     			}
     };
        class IntPhone : public NatPhone
        {
        	private:
        		int ncode;
        		public:
        			void input()
        			{
        			cout<<"Enter country code:";
        			cin>>ncode;
        			NatPhone::input();
        			}
        			void show()
        			{
        			cout<<ncode<<"";
        			NatPhone::show();
        			}
        };
           main()
           {
           	IntPhone p;
           	p.input();
           	p.show();
           }

Leave a Reply