Inheritence

Download as pdf or txt
Download as pdf or txt
You are on page 1of 56

PG-DAC

NAME:Ankur Saini
EMAIL: [email protected]
PH: 8439910399
ASSIGNMENT C++ (INHERITANCE) DAC 2020

IMPLEMENT ALL THE QUESTIONS ON SUITABLE TYPE OF INHERITANCE BASED


ON THE QUESTIONS

1.Create two classes named Mammals and MarineAnimals. Create another class named
BlueWhale which inherits both the above classes. Now, create a function in each of these
classes which prints "I am mammal", "I am a marine animal" and "I belong to both the
categories: Mammals as well as Marine Animals" respectively. Now, create an object for
each of the above class and try calling
1 - function of Mammals by the object of Mammal
2 - function of MarineAnimal by the object of MarineAnimal
3 - function of BlueWhale by the object of BlueWhale
4 - function of each of its parent by the object of BlueWhale

2.Make a class named Fruit with a data member to calculate the number of fruits in a basket.
Create two other class named Apples and Mangoes to calculate the number of apples and
mangoes in the basket. Print the number of fruits of each type and the total number of fruits
in the basket.

3.We want to calculate the total marks of each student of a class in Physics, Chemistry and
Mathematics and the average marks of the class. The number of students in the class are
entered by the user. Create a class named Marks with data members for roll number, name
and marks. Create three other classes inheriting the Marks class, namely Physics, Chemistry
and Mathematics, which are used to define marks in individual subject of each student. Roll
number of each student will be generated automatically.

4.We want to store the information of different vehicles. Create a class named Vehicle with
two data member named mileage and price. Create its two subclasses
*Car with data members to store ownership cost, warranty (by years), seating capacity and
fuel type (diesel or petrol).
*Bike with data members to store the number of cylinders, number of gears, cooling type(air,
liquid or oil), wheel type(alloys or spokes) and fuel tank size(in inches)
Make another two subclasses Audi and Ford of Car, each having a data member to store the
model type. Next, make two subclasses Bajaj and TVS, each having a data member to store
the make-type.
Now, store and print the information of an Audi and a Ford car (i.e. model type, ownership
cost, warranty, seating capacity, fuel type, mileage and price.) Do the same for a Bajaj and a
TVS bike.
5.Create a class named Shape with a function that prints "This is a shape". Create another
class named Polygon inheriting the Shape class with the same function that prints "Polygon is
a shape". Create two other classes named Rectangle and Triangle having the same function
which prints "Rectangle is a polygon" and "Triangle is a polygon" respectively. Again, make
another class named Square having the same function which prints "Square is a rectangle".
Now, try calling the function by the object of each of these classes.

6. All the banks operating in India are controlled by RBI. RBI has set a well defined
guideline (e.g. minimum interest rate, minimum balance allowed, maximum withdrawal limit
etc) which all banks must follow. For example, suppose RBI has set minimum interest rate
applicable to a saving bank account to be 4% annually; however, banks are free to use 4%
interest rate or to set any rates above it. Write a program to implement bank functionality in
the above scenario. Note: Create few classes namely Customer, Account, RBI (Base Class)
and few derived classes (SBI, ICICI, PNB etc). Assume and implement required member
variables and functions in each class.
7. Design three classes STUDENT ,EXAM and RESULT. The STUDENT class has data
members such as rollno, name. create a class EXAM by inheriting the STUDENT class. The
EXAM class adds data members representing the marks scored in six subjects. Derive the
RESULT from the EXAM class and has its own data members such as totalmarks. Write a
program to model this relationship.

8. What is the difference between containership and inheritance?

9. IMPLEMENT with PROGRAM.

10. Describe INHERITANCE TYPES : PRIVATE, PROTECTED and PUBLIC – the


differences .
Ans 1:

#include <iostream>

using namespace std;

class Mammals {

public:

void fn1() {

cout << "I am mammal" << endl;

};

class MarineAnimals {

public:

void fn2() {

cout << "I am a marine animal" << endl;

};

class BlueWhale : public Mammals, public MarineAnimals {

public:

void fn3() {

cout << "I belong to both the categories: Mammals as well as Marine
Animals" << endl;

};

int main()

Mammals mm;
MarineAnimals ma;

BlueWhale bw;

cout<<"func of Mammals by obj of Mammals"<<endl;

mm.fn1();

cout<<endl;

cout<<"func of MarineAnimals by obj of MarineAnimals"<<endl;

ma.fn2();

cout<<endl;

cout<<"func of BlueWhale by obj of BlueWhale"<<endl;

bw.fn3();

cout<<endl;

cout<<"func of Mammals by obj of BlueWhale"<<endl;

bw.fn1();

cout<<endl;

cout<<"func of MarineAnimals by obj of BlueWhale"<<endl;

bw.fn2();

return 0;

}
Ans 2:

#include<iostream>

using namespace std;

class fruit

int fr;

public :

fruit(int x)

fr=x;

void call1()

cout<<"no of fruits :"<<fr;

}
};

class apples

int ap;

public :

apples(int y)

ap=y;

void call2()

cout<<"\nno of apples :"<<ap;

};

class mangoes

int man;

public :

mangoes(int z)

man=z;

void call3()

{
cout<<"\n no of mangoes : "<<man;

};

int main()

fruit f(10);

apples a(3);

mangoes m(5);

f.call1();

a.call2();

m.call3();

return 0;
}
Ans 3:

#include<iostream>

using namespace std;

class marks

public:

int roll,j;

string name[10];

int marks[5];

void ini()

for(j=0;j<5;j++)

cout<<"enter name :";

cin>>name[j];

}
}

string nmr(int j)

return(name[j]);

};

class physics :public marks

public:

int i;

void init1()

for(i=0;i<5;i++)

cout<<"student roll no "<<i+1;

cout<<"\nenter marks ";

cin>>marks[i];

int ph(int i)

return(marks[i]);

}
};

class chemistry :public marks

public :

int i;

void init2()

for(i=0;i<5;i++)

cout<<"student roll no "<<i+1<<name[i];

cout<<"\nenter marks ";

cin>>marks[i];

int ch(int i)

return(marks[i]);

};

class math :public marks

public :

int i;
void init3()

for(i=0;i<5;i++)

cout<<"student roll no "<<i+1<<name[i];

cout<<"\nenter marks ";

cin>>marks[i];

int mh(int i)

return(marks[i]);

};

int main()

int sum=0;

marks mr;

mr.ini();

physics p;

chemistry c;

math m;

cout<<"ENTER THE MARKS IN PHYSICS \n";

p.init1();
cout<<"ENTER THE MARKS IN CHEMISTRY \n";

c.init2();

cout<<"ENTER THE MARKS IN MATHEMATICS \n";

m.init3();

cout<<"TOTAL AND AVERAGE MARKS OF THE STUDENTS \n";

for(int i=0;i<5;i++)

cout<<"\nstudent roll no"<<i;

cout<<"\ntotal marks :";

sum=p.ph(i)+c.ch(i)+m.mh(i);

cout<<sum;

cout<<"\nAVERAGE MARKS :";

cout<<sum/3;

}
}
Ans 4:

#include<iostream>

using namespace std;

class vehicle

protected:

int mileage,price;

public:

void getdata()

cout<<"enter the mileage of the vehicle:\t";

cin>>mileage;

cout<<"enter the price of the vehicle:\t";

cin>>price;

void display1()

cout<<"mileage:\t"<<mileage<<"\nprice:\t"<<price<<endl;

}
};

class car:public vehicle

protected:

int ownership_cost, warranty,seating_capacity;

char fuel_type[20];

public:

void getcar()

cout<<"enter the ownership cost\n";

cin>>ownership_cost;

cout<<"enter the warranty by years\n";

cin>>warranty;

cout<<"enter the seating capacity\n";

cin>>seating_capacity;

cout<<"enter the fule type(diesel or petrol\n";

cin>>fuel_type;

void display2()

cout<<"\nownership
cost:\t"<<ownership_cost<<"\n"<<"\nwarranty:\t"<<warranty;

cout<<"\nseating capacity:\t"<<seating_capacity<<"\nfule
type:\t"<<fuel_type;
}

};

class bike:public vehicle

private:

int no_of_cylinder,no_of_gears,fuel_tank_size;

char cooling_type[20],wheel_type[20];

public:

void getbike()

cout<<"enter the no of cylinders\n";

cin>>no_of_cylinder;

cout<<"enter the no of gears\n";

cin>>no_of_gears;

cout<<"enter the fuel tank size(in inches)\n";

cin>>fuel_tank_size;

cout<<"enter the cooling type(air liquid or oil)\n";

cin>>cooling_type;

cout<<"enter the wheel type(alloy or spokes)\n";

cin>>wheel_type;

void display2()

{
cout<<"\n no of cylinders:\t"<<no_of_cylinder<<"\nno of
gears:\t"<<no_of_gears;

cout<<"\nfuel tank size:\t"<<fuel_tank_size<<"\ncooling


type:\t"<<cooling_type;

cout<<"\nwheel type:\t"<<wheel_type;

};

class audi:public car

protected:

char model_type[20];

public:

void get_model()

cout<<"enter the the model type(A6,A8 L,Q8)\n";

cin>>model_type;

void display3()

cout<<"\nmodel type:\t"<<model_type;

void fun()

get_model();
getcar();

getdata();

display1();

display2();

display3();

};

class ford:public car

protected:

char model_type[20];

public:

void get_model()

cout<<"enter the the model type(endeavour,figo,aspire)\n";

cin>>model_type;

void display3()

cout<<"\nmodel type:\t"<<model_type;

void fun()

{
get_model();

getcar();

getdata();

display1();

display2();

display3();

};

class bajaj:public bike

protected:

char make_type[20];

public:

void get_make()

cout<<"enter the the make type(chetak,dominar,pulsar)\n";

cin>>make_type;

void display3()

cout<<"\nmake type:\t"<<make_type;

void fun()
{

get_make();

getbike();

getdata();

display1();

display2();

display3();

};

class tvs:public bike

private:

char make_type[20];

public:

void get_make()

cout<<"enter the the make type(chetak,dominar,pulsar)\n";

cin>>make_type;

void display3()

cout<<"\nmake type:\t"<<make_type;
}

void fun()

get_make();

getbike();

getdata();

display1();

display2();

display3();

};

int main()

tvs t;

bajaj b;

audi a;

ford f;

int c,d;

cout<<"enter the choice\n1:car\n2:bike\n3:Exit(0)\n";

cin>>c;

if(c==1)

cout<<"enter the choice\n1:Audi\n2:Ford\n3:Exit(0)\n";


cin>>d;

else

cout<<"enter the choice\n1:Bajaj\n2:Tvs\n3:Exit(0)\n";

cin>>d;

switch(c){

case 1:

switch(d)

case 1:

a.fun();

break;

case 2:

f.fun();

break;

case 3:

exit(0);

}
}

break;

case 2:

switch(d)

case 1:

b.fun();

break;

case 2:

t.fun();

break;

case 3:

exit(0);

default:

cout<<"enter the correct option\n";

case 3:

exit(0);

default:

cout<<"enter the correct option\n";


}

return 0;
}

Ans5:

#include<iostream>

using namespace std;

class shape

public:

void init()

cout<<"this is a shape\n";

};

class polygon :public shape

public :

void init()

cout<<"polygon is a shape\n";

};
class rectangle

public :

void init()

cout<<"rectangle is a polygon\n";

};

class traingle

public :

void init()

cout<<"traingle is a polygon\n";

};

class square

public :

void init()

cout<<"square is a rectangle\n";

};
int main()

shape s;

s.init();

polygon p;

p.init();

traingle t;

t.init();

rectangle r;

r.init();

square sq;

sq.init();
}
Ans 6:

#include<iostream>

using namespace std;

class Customer

protected:

int account_no;

char name[10];

public:

void getdata()

cout<<"enter the customer name :";

cin>>name;

cout<<"enter the account no: ";

cin>>account_no;

};

class rbi

public :

void detail()
{

cout<<"intrest rate of RBI decided 4%\n";

cout<<"minimum balance of any account RBI decided is 1000r-\n";

cout<<"maximum withdrawl limit is 20000r-\n";

};

class sbi

float r=4,t=1,si,w,credit;

public:

void cre()

cout<<"please enter the credit amount\n";

cin>>credit;

double getinterestrate()

si=(credit*r*t)/100;

credit=si+credit;

return credit;

double getwithdrawallimit()

{
cout<<"enter the withdrawl amount";

cin>>w;

if(w>=20000)

cout<<"withdrawl limit is 200000";

else

credit=credit-w;

return credit;

double balance()

cout<<"balance:\t"<<credit;

return credit;

};

class icici

float r=4,t=1,si,w,credit;

public:

void cre()

{
cout<<"please enter the credit amount\n";

cin>>credit;

double getinterestrate()

si=(credit*r*t)/100;

credit=si+credit;

return credit;

double getwithdrawallimit()

cout<<"enter the withdrawl amount";

cin>>w;

if(w>=20000)

cout<<"withdrawl limit is 200000";

else

credit=credit-w;

return credit;

}
double balance()

cout<<"balance:\t"<<credit;

return credit;

};

class pnb

float r=4,t=1,si,w,credit,ins;

public:

void cre()

cout<<"please enter the credit amount\n";

cin>>credit;

double getinterestrate()

si=(credit*r*t)/100;

ins=si+credit;

return ins;

double getwithdrawallimit()
{

cout<<"enter the withdrawl amount";

cin>>w;

if(w>=20000)

cout<<"withdrawl limit is 200000";

else

credit=credit-w;

return credit;

double balance()

cout<<"balance:\t"<<credit;

return credit;

};

int main()

int a;

sbi s;

icici i;
pnb p;

Customer c;

c.getdata();

rbi r;

r.detail();

cout<<"choose the bank\n1:SBI\n2:ICICI\n3:PNB\n";

cin>>a;

switch(a)

case 1:

s.cre();

cout<<"INTEREST RATE AFTER 1 YR \n";

cout<<s.getinterestrate()<<endl;

s.getwithdrawallimit();

s.balance();

break;

case 2:

i.cre();

cout<<"INTEREST RATE AFTER 1 YR \n";

cout<<i.getinterestrate()<<endl;

i.getwithdrawallimit();

i.balance();
break;

case 3:

p.cre();

cout<<"INTEREST RATE AFTER 1 YR \n";

cout<<p.getinterestrate()<<endl;

p.getwithdrawallimit();

p.balance();

break;

case 4:

exit(0);

default:

cout<<"please choose the correct option\n";

}
}
Ans 7:

#include<iostream>

using namespace std;

class student

char name[25];

int rno;

public:

void input()

cout<<"\nEnter name: ";

gets(name);

cout<<"\nEnter roll no: ";

cin>>rno;

void output()

cout<<"\nNAME : "<<name;

cout<<"\nROLL NO. : "<<rno;

};

class exam: public student


{

float mks[6];

public:

void indata();

float add();

};

void exam::indata()

int i;

input();

cout<<"\nEnter marks in six subjects (out of 100):\n";

for(i=0;i<6;i++)

cin>>mks[i];

float exam::add()

int i=0;

float sum=0;

for(i=0;i<6;i++)

sum=sum+mks[i];

}
return sum;

class result: public exam

float tm;

float per;

public:

void display()

tm=add();

per=tm/6;

output();

cout<<"\nTotal Marks: "<<tm<<"/600";

cout<<"\nPercentage : "<<per<<"%";

};

main()

result r;

r.indata();

r.display();
return 0;
}
Ans 8:

Inheritance is the ability for a class to inherit properties and behavior from a parent class by
extending it. Inheritance essentially provides code reuse by allowing extending properties and
behavior of an existing class by a newly defined class. If class A extends B, then class B is called the
parent class (or super class) and class A is called the child class (or derived class/sub class). In this
example scenario, class A will inherit all public and protected attributes and methods of the super
class (B). The subclass can optionally override (provide new or extended functionality to methods)
the behavior inherited from the parent class. Inheritance represents an “is-a” relationship in OOP.
This essentially means that A is also a B. In other words, B can be the class with a general description
of a certain real world entity but A specifies a certain specialization. In a real world programming
problem, the Person class could be extended to create the Employee class. This is called
specialization. But you could also first create the Employee class and then generalize it to a Person
class as well (i.e. generalization). In this example, the Employee will have all the properties and
behavior of the Person (i.e. Employee is also a Person) and may contain some additional
functionality (so, Person is not an Employee) as well.

-> When you want to force the new type to be the same type as the base class.

for eg->

1)computer system is an electronic device

2)Car is a vehicle

Syntax:

class subclass_name : access_mode base_class_name

//body of subclass

};

// C++ program to demonstrate implementation

// of Inheritance

#include <bits/stdc++.h>

using namespace std;


//Base class

class Parent

public:

int id_p;

};

// Sub class inheriting from Base Class(Parent)

class Child : public Parent

public:

int id_c;

};

//main function

int main()

Child obj1;

// An object of class child has all data members

// and member functions of class parent

obj1.id_c = 7;

obj1.id_p = 91;

cout << "Child id is " << obj1.id_c << endl;

cout << "Parent id is " << obj1.id_p << endl;

return 0;

Output:
Child id is 7

Parent id is 91

Containership is the ability of a class to contain objects of different classes as member data. For
example, class A could contain an object of class B as a member. Here, all the public methods (or
functions) defined in B can be executed within the class A. Class A becomes the container, while
class B becomes the contained class. Containership is also referred to as Composition. In this
example, it can be said that class A is composed of class B. In OOP, Containership represents a “has-
a” relationship. It is important to note that, even though the container has access to execute all the
public methods of the contained class, it is not able to alter or provide additional functionality. When
it comes to a real world programming problem, an object of class TextBox may be contained in the
class Form, and thus can be said that a Form contains a TextBox (or alternatively, a Form is
composed of a TextBox).

-> When features of existing class are wanted inside your new class, but, not its interface
for eg->
1)computer system has a hard disk
2)car has an Engine, chassis, steering wheels.

Syntax for Containership:

// Class that is to be contained

class first {

};

// Container class

class second {

// creating object of first

first f;

};

// CPP program to illustrate

// concept of Containership
#include <iostream>

using namespace std;

class first {

public:

void showf()

cout << "Hello from first class\n";

};

// Container class

class second {

// creating object of first

first f;

public:

// constructor

second()

// calling function of first class

f.showf();

};

int main()

// creating object of second

second s;

}
Output:

Hello from first class

Although Inheritance and Containership are two OOP concepts, they are quite different in what they
allow the programmer to achieve. Inheritance is the ability for a class to inherit properties and
behavior from a parent class by extending it, while Containership is the ability of a class to contain
objects of different classes as member data. If a class is extended, it inherits all the public and
protected properties/behavior and those behaviors may be overridden by the subclass. But if a class
is contained in another, the container does not get the ability to change or add behavior to the
contained. Inheritance represents an “is-a” relationship in OOP, while Containership represents a
“has-a” relationship.
Ans 9:

IMPLEMENT with PROGRAM

#include<iostream>

using namespace std;

class vehicle

protected:

int mileage,price;

public:

void getdata()

cout<<"enter the mileage of the vehicle:\t";

cin>>mileage;

cout<<"enter the price of the vehicle:\t";

cin>>price;

};

class car:public vehicle

protected:

int ownership_cost, warranty,seating_capacity;

char fuel_type;

public:

void getcar()

cout<<"enter the ownership cost\n";

cin>>ownership_cost;

cout<<"enter the warranty bu years\n";


cin>>warranty;

cout<<"enter the seating capacity\n";

cin>>seating_capacity;

cout<<"enter the fule type(diesel or petrol\n";

cin>>fuel_type;

};

class bike:public vehicle

protected:

int no_of_cylinder,no_of_gears,fuel_tank_size;

char cooling_type,wheel_type;

public:

void getbike()

cout<<"enter the no of cylinders\n";

cin>>no_of_cylinder;

cout<<"enter the no of gears\n";

cin>>no_of_gears;

cout<<"enter the fuel tank size(in inches)\n";

cin>>fuel_tank_size;

cout<<"enter the cooling type(air liquid or oil)\n";

cin>>cooling_type;

cout<<"enter the wheel type(alloy or spokes)\n";

cin>>wheel_type;

void display()

};
int main()

bike b;

b.getbike();

b.getdata();

b.display();

return 0;

}
Ans10:

Describe INHERITANCE TYPES : PRIVATE, PROTECTED and PUBLIC – the differences .

Data hiding is one of the important features of Object Oriented Programming which allows
preventing the functions of a program to access directly the internal representation of a class type.
The access restriction to the class members is specified by the labeled access modifiers: public,
private, and protected sections within the class body.

Example Code

class Base {

public:

// public members go here

protected:

// protected members go here

private:

// private members go here

};

The following table will illustrate this difference:

Public Protected Private


Members Members Members
Public
public protected private
Inheritance
Protected
protected protected private
inheritance
Private
private private private
inheritance

A public member is accessible from anywhere outside the class but within a program. You can set
and get the value of public variables without any member.

A private member variable or function cannot be accessed, or even viewed from outside the class.
Only the class and friend functions can access private members.

A protected member variable or function is very similar to a private member but it provided one
additional benefit that they can be accessed in child classes which are called derived classes.
Accessibility in Public Inheritance

private protected public


Accessibility
variables variables variables

Accessible from own class? yes yes yes

Accessible from derived class? no yes yes

Accessible from 2nd derived


no yes yes
class?

Accessibility in Protected Inheritance

private protected
Accessibility public variables
variables variables

Accessible from own class? yes yes yes

yes
Accessible from derived
no yes (inherited as protected
class?
variables)

Accessible from 2nd


no yes yes
derived class?

private
Accessibility protected variables public variables
variables

Accessible from own


yes yes yes
class?

yes yes
Accessible from derived
no (inherited as private (inherited as private
class?
variables) variables)

Accessible from 2nd


no no no
derived class?
Accessibility in Private Inheritance

Example of public, protected and private inheritance in C++

class base

public:

int x;

protected:

int y;

private:

int z;

};

class publicDerived: public base

// x is public

// y is protected

// z is not accessible from publicDerived

};

class protectedDerived: protected base

// x is protected

// y is protected

// z is not accessible from protectedDerived

};

class privateDerived: private base

// x is private

// y is private
// z is not accessible from privateDerived

n the above example, we observe the following things:

base has three member variables: x, y and z which are public, protected and private member
respectively.

publicDerived inherits variables x and y as public and protected. z is not inherited as it is a private
member variable of base.

protectedDerived inherits variables x and y. Both variables become protected. z is not inherited

If we derive a class derivedFromProtectedDerived from protectedDerived, variables x and y are also


inherited to the derived class.

privateDerived inherits variables x and y. Both variables become private. z is not inherited

If we derive a class derivedFromPrivateDerived from privateDerived, variables x and y are not


inherited because they are private variables of privateDerived.

Private Inheritance Example Program

In order to understand how to use private inheritance, let us look at the following example program
that uses two classes: the parent and the child classes.

# cat p1.cpp

#include <iostream>

using namespace std;

class Parent{

public:

void parentMethod( void ){ cout<<"Inside parent method"<<endl;}

};

class Child : private Parent{


public:

void childMethod( void){

cout<<"Inside child method"<<endl;

parentMethod();

};

int main( void ){

Child C;

C.childMethod();

return 0;

The following is the output of the above program:

# g++ p1.cpp

# ./a.out

Inside child method

Inside parent method

Protected Inheritance Example Code

The following example explains how the protected inheritance could be used in the program.

# cat p2.cpp

#include <iostream>

using namespace std;


class GrandParent{

public:

void grandParentMethod( void ){ cout<<"Method in the grand parent class"<<endl; }

};

class Parent : protected GrandParent{

public:

void parentMethod( void ){ cout<<"Method in the parent class"<<endl; }

};

class Child: protected Parent{

public:

void

childMethod( void ){

cout<<"Method in the child class"<<endl;

parentMethod();

grandParentMethod();

};

int

main( void ){

Child C;

C.childMethod();

return 0;

The following is the output of the above program:


# g++ p2.cpp

# ./a.out

Method in the child class

Method in the parent class

Method in the grand parent class

You might also like