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

Write a class Book that contains the attributes BookID, book name and
price. It also contains member functions to input and show its attributes.
Write another class Writer that contains the attributes writer name, address
and number of books written by him. It contains an array of Book objects as its member.
The length of array should be 5 to store the data of five books.
It also contains member functions to input and display its attributes.


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

class Book{
	protected:
		int bid;
		char bname[50];
		float price;
		public:
			void input()
			{
				cout<<"Enter book id:";
				cin>>bid;
				cout<<"Enter book name:";
				gets(bname);
				cout<<"Enter book price:";
				cin>>price;
			}
			void show()
			{
			cout<<"Book ID:"<<bid<<endl;
			cout<<"Book name:"<<bname<<endl;
			cout<<"Price:"<<price<<endl;
			}
};
    class Writer
    {
    	protected:
    		char name[50], address[100];
    		int books;
    		Book bk[5];
    		public:
    			void input()
    			{
    		cout<<"Enter writer name:";
    		gets(name);
    		cout<<"Enter writer address:";
    		gets(address);
    		cout<<"Enter number of books written:";
    		cin>>books;
    		cout<<"Enter detail of five books:"<<endl;
    		for(int i=0; i<5; i++)
    		bk[i].input();
    			}
    		void show()
    			{
    		cout<<"\nWriter name:"<<name<<endl;
    		cout<<"Address:"<<address<<endl;
    		cout<<"Number of books:"<<books<<endl;
    		cout<<"\nDetail of five books:\n"<<endl;
    		for(int i=0; i<5; i++)
    		bk[i].show();
    			}
    };
       main()
       {
       	Writer w;
       	w.input();
       	w.show();
       }
 

Leave a Reply