Inheritance

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 41

Inheritance in C++

Inheritance is a feature or a process in which, new classes are created from the existing classes. The new
class created is called “derived class” or “child class” and the existing class is known as the “base class”
or “parent class”. The derived class now is said to be inherited from the base class. When we say derived
class inherits the base class, it means, the derived class inherits all the properties of the base class, without
changing the properties of base class and may add new features to its own. These new features in the
derived class will not affect the base class. The derived class is the specialized class for the base class.

PERSON

Id
Base class/Parent class
Name

Address

FatherName

MotherName

..

STUDENT

course

fee Derived class/Child class

..

..

void set_data();

1
Derived Classes

A Derived class is defined as the class derived from the base class.

Syntax:
class <derived_class_name> : <access-specifier> <base_class_name>
{
//body
}
Where
class -- keyword to create a new class
derived_class_name -- name of the new class, which will inherit the base class
access-specifier -- either of private, public or protected. Is neither is specified, PRIVATE is taken as default
base-class-name -- name of the base class

Example:
1. class ABC : private XYZ //private derivation
{ }
2. class ABC : public XYZ //public derivation
{ }
3. class ABC : protected XYZ //protected derivation
{ }
4. class ABC: XYZ //private derivation by default
{ }

Note:
o When a base class is privately inherited by the derived class, public members of the base class
becomes the private members of the derived class and therefore, the public members of the base
class can only be accessed by the member functions of the derived class. They are inaccessible to
the objects of the derived class.
o On the other hand, when the base class is publicly inherited by the derived class, public members
of the base class also become the public members of the derived class. Therefore, the public
members of the base class are accessible by the objects of the derived class as well as by the
member functions of the derived class.

2
Example 1: define member function without argument within the class
#include<iostream>
using namespace std;
class Person
{
int id;
char name[100];
public:
void set_p()
{
cout<<"Enter the Id:";
cin>>id;
fflush(stdin);
cout<<"Enter the Name:";
cin.get(name,100);
}
void display_p()
{
cout<<endl<<id<<"\t"<<name;
}
};
class Student: private Person
{
char course[50];
int fee;
public:
void set_s()
{
set_p();
cout<<"Enter the Course Name:";
fflush(stdin);
cin.getline(course,50);
cout<<"Enter the Course Fee:";
cin>>fee;
}

3
void display_s()
{
display_p();
cout<<"t"<<course<<"\t"<<fee;
}
};

main()
{
Student s;
s.set_s();
s.display_s();
return 0;
}

Example 2: define member function without argument outside the class


#include<iostream>
using namespace std;
class Person
{
int id;
char name[100];
public:
void set_p();
void display_p();
};
void Person::set_p()
{
cout<<"Enter the Id:";
cin>>id;
fflush(stdin);
cout<<"Enter the Name:";
cin.get(name,100);
}

4
void Person::display_p()
{
cout<<endl<<id<<"\t"<<name;
}
class Student: private Person
{
char course[50];
int fee;
public:
void set_s();
void display_s();
};
void Student::set_s()
{
set_p();
cout<<"Enter the Course Name:";
fflush(stdin);
cin.getline(course,50);
cout<<"Enter the Course Fee:";
cin>>fee;
}
void Student::display_s()
{
display_p();
cout<<"t"<<course<<"\t"<<fee;
}
main()
{
Student s;
s.set_s();
s.display_s();
return 0;
}

Example 3: define member function with argument within the class

5
#include<iostream>
#include<string.h>
using namespace std;
class Person
{
int id;
char name[100];
public:
void set_p(int id,char n[])
{
this->id=id;
strcpy(this->name,n);
}
void display_p()
{
cout<<endl<<id<<"\t"<<name;
}
};
class Student: private Person
{ char course[50];
int fee;
public:
void set_s(int id,char n[],char c[],int f)
{
set_p(id,n);
strcpy(course,c);
fee=f;
}
void display_s()
{
display_p();
cout<<"t"<<course<<"\t"<<fee;
}
};

6
main()
{
Student s;
s.set_s(1001,"Manjeet kumar","Ph.D",2000);
s.display_s();
return 0;
}

Example 3: define member function with argument outside the class


#include<iostream>
#include<string.h>
using namespace std;
class Person
{
int id;
char name[100];
public:
void set_p(int,char[]);
void display_p();
};

void Person::set_p(int id,char n[])


{
this->id=id;
strcpy(this->name,n);
}

void Person::display_p()
{
cout<<endl<<id<<"\t"<<name;
}
class Student: private Person
{
char course[50];
int fee;
public:
void set_s(int,char[],char[],int);
void display_s();
};
void Student::set_s(int id,char n[],char c[],int f)
{
set_p(id,n);
strcpy(course,c);
fee=f;
}

7
void Student::display_s()
{
display_p();
cout<<"t"<<course<<"\t"<<fee;
}

main()
{
Student s;
s.set_s(1001,"Manjeet kumar","Ph.D",2000);
s.display_s();
return 0;
}

Types Of Inheritance

C++ supports five types of inheritance:

o Single inheritance
o Multilevel inheritance
o Multiple inheritance
o Hierarchical inheritance
o Hybrid inheritance

Single Inheritance
 Single inheritance is defined as the inheritance in which a derived class is inherited from the only
one base class.

A Eg:
Animal Person

B Dog Student
Fig: Single Inheritance

Here ‘A’ is the base class and 'B' is the derived class.

Syntax:

8
class A
{
... .. ...
};

class B: public A
{
... .. ...
};

Example 1:
#include<iostream>
using namespace std;
class A
{
protected:
int a;
public:
void set_A()
{
cout<<"Enter the Value of A=";
cin>>a;

}
void disp_A()
{
cout<<endl<<"Value of A="<<a;
}
};

class B: public A

9
{
int b,p;
public:
void set_B()
{
set_A();
cout<<"Enter the Value of B=";
cin>>b;
}

void disp_B()
{
disp_A();
cout<<endl<<"Value of B="<<b;
}

void cal_product()
{
p=a*b;
cout<<endl<<"Product of "<<a<<" * "<<b<<" = "<<p;
}

};

main()
{

B _b;
_b.set_B();
_b.cal_product();

return 0;

10
Example 2:
#include<iostream>
using namespace std;
class A
{
protected:
int a;
public:
void set_A(int x)
{
a=x;
}
void disp_A()
{
cout<<endl<<"Value of A="<<a;
}
};

class B: public A
{
int b,p;
public:
void set_B(int x,int y)
{
set_A(x);
b=y;
}

11
void disp_B()
{
disp_A();
cout<<endl<<"Value of B="<<b;
}

void cal_product()
{
p=a*b;
cout<<endl<<"Product of "<<a<<" * "<<b<<" = "<<p;
}

};

main()
{
B _b;
_b.set_B(4,5);
_b.cal_product();

return 0;
}

Example 3:
#include<iostream>
using namespace std;
class A
{
protected:
int a;
public:
void set_A(int x)
{
a=x;

12
}
void disp_A()
{
cout<<endl<<"Value of A="<<a;
}
};

class B: public A
{
int b,p;
public:
void set_B(int y)
{
b=y;
}

void disp_B()
{

cout<<endl<<"Value of B="<<b;
}

void cal_product()
{
p=a*b;
cout<<endl<<"Product of "<<a<<" * "<<b<<" = "<<p;
}

};

main()
{

B _b;

13
_b.set_A(10);
_b.set_B(4);
_b.disp_A();
_b.disp_B();

_b.cal_product();

return 0;

Example 4:
#include<iostream>
using namespace std;
class A
{
protected:
int a;
public:
void set_A(int x)
{
a=x;
}
void disp_A()
{
cout<<endl<<"Value of A="<<a;
}
};

class B: private A
{
int b,p;
public:
void set_B(int y)

14
{
b=y;
}

void disp_B()
{

cout<<endl<<"Value of B="<<b;
}

void cal_product()
{
p=a*b;
cout<<endl<<"Product of "<<a<<" * "<<b<<" = "<<p;
}

};

main()
{

B _b;
_b.set_A(10);
_b.set_B(4);
_b.disp_A();
_b.disp_B();

_b.cal_product();

15
return 0;
}

16
Multilevel Inheritance
Multilevel inheritance is a process of deriving a class from another derived class.

Fig: Multilevel Inheritance

Syntax:

class A
{
... .. ...
};
class B: public A
{
... .. ...
};
class C: public B
{
... ... ...
};

Example:
#include<iostream>
using namespace std;
class A
{
protected:
int a;
public:
void set_A()
{
cout<<"Enter the Value of A=";
cin>>a;

17
void disp_A()
{
cout<<endl<<"Value of A="<<a;
}
};

class B: public A
{
protected:
int b;
public:
void set_B()
{
cout<<"Enter the Value of B=";
cin>>b;
}

void disp_B()
{
cout<<endl<<"Value of B="<<b;
}

};

class C: public B
{
int c,p;
public:
void set_C()
{
cout<<"Enter the Value of C=";
cin>>c;
}

void disp_C()
{
cout<<endl<<"Value of C="<<c;
}

void cal_product()
{
p=a*b*c;
cout<<endl<<"Product of "<<a<<" * "<<b<<" * "<<c<<" = "<<p;
}

};

main()
{

C _c;

18
_c.set_A();
_c.set_B();
_c.set_C();
_c.disp_A();
_c.disp_B();
_c.disp_C();
_c.cal_product();

return 0;

19
Multiple Inheritance

A class can be derived from more than one base class.

A B

Fig: Multiple Inheritance

Eg: (i) A CHILD class is derived from FATHER and MOTHER class

(ii) A PETROL class is derived from LIQUID and FUEL class.

Syntax:

class A
{
... .. ...
};
class B
{
... .. ...
};
class C: public A,public B
{
... ... ...
};

Example:
#include <iostream>
using namespace std;
class A
{
protected:
int a;
public:
void get_a(int n)
{
a = n;
}
};

20
class B
{
protected:
int b;
public:
void get_b(int n)
{
b = n;
}
};
class C : public A,public B
{
public:
void display()
{
cout << "The value of a is : " <<a<< endl;
cout << "The value of b is : " <<b<< endl;
cout<<"Product of a and b is : "<<a*b;
}
};
int main()
{
C c;
c.get_a(10);
c.get_b(20);
c.display();

return 0;
}

21
Ambiguity Resolution in Inheritance

Ambiguity can be occurred in using the multiple inheritances when a function with the same name occurs
in more than one base class.

A B
display() display()

#include <iostream>
using namespace std;
class A
{
public:
void display()
{
cout << "Class A" << endl;
}
};
class B
{
public:
void display()
{
cout << "Class B" << endl;
}
};
class C : public A, public B
{
public:
void show()
{
display();
}
};
int main()
{
C c;
c.show();
return 0;
}

22
The issue can be resolved by using the scope resolution operator with the function. In the given
example, the derived class code can be rewritten as:

class C : public A, public B


{
void view()
{
A :: display(); // Calling the display() function of class A.
B :: display(); // Calling the display() function of class B.

}
};

23
Hierarchical Inheritance

Hierarchical inheritance is defined as the process of deriving more than one class from a base class.

Fig: Hierarchical inheritance

Syntax:

class A
{
// body of the class A.
}
class B : public A
{
// body of class B.
}
class C : public A
{
// body of class C.
}
class D : public A
{
// body of class D.
}

24
#include <iostream>

using namespace std;

class Shape // Declaration of base class.

public:

int a;

int b;

void get_data(int n,int m)

a= n;

b = m;

};

class Rectangle : public Shape // inheriting Shape class

public:

int rect_area()

int result = a*b;

return result;

};

25
class Triangle : public Shape // inheriting Shape class

public:

int triangle_area() {

float result = 0.5*a*b;

return result;

};

int main() {

Rectangle r;

Triangle t;

int length,breadth,base,height;

cout << "Enter the length and breadth of a rectangle: " << endl;

cin>>length>>breadth;

r.get_data(length,breadth);

int m = r.rect_area();

cout << "Area of the rectangle is : " <<m<< endl;

std::cout << "Enter the base and height of the triangle: " << endl;

cin>>base>>height;

t.get_data(base,height);

float n = t.triangle_area();

std::cout <<"Area of the triangle is: “<< n<<endl;

return 0;

26
}

Hybrid Inheritance

Hybrid inheritance is a combination of more than one type of inheritance.

Fig: Hybrid Inheritance

27
A

B C

#include <iostream>
using namespace std;
class A
{
protected:
int a;
public:
void get_a()
{
cout << "Enter the value of 'a' : ";
cin>>a;
}
};

class B : public A
{
protected:
int b;
public:
void get_b()
{
cout << "Enter the value of 'b' : ";
cin>>b;
}
};
class C
{
protected:
int c;
public:
void get_c()
{
cout << "Enter the value of c is : ";
cin>>c;
}
};

class D : public B, public C


{
protected:
int d;

28
public:
void mul()
{
get_a();
get_b();
get_c();
cout << "Multiplication of a,b,c is : " <<a*b*c;
}
};

int main()
{
D d;
d.mul();
return 0;
}

29
Function Overriding

 The mechanism of defining the function with the same name and signature in both the base class
and derived class is known as function overriding.
 If derived class defines same function as defined in its base class, it is known as function
overriding in C++.
 Function overriding is used to achieve runtime polymorphism.
 It enables you to provide specific implementation of the function which is already provided by its
base class.
#include<iostream>
using namespace std;
class XYZ
{
public:
void display() //overridden function
{
cout<<"I am in class XYZ";
}
};

class ABC: public XYZ


{
public:
void display() //overriding function
{
cout<<"I am in class ABC";
}
};

int main()
{
ABC a1;
a1.display();
retrun 0;
}

Here, the display() function of derived class ABC has overriding the display function of base class XYZ.
In main function an object of the derived class (a1) is created. Now, when the display() function is called
with respect to the derived class object, then derived class function called. It means that, whenever a
function is called with respect to an object of a class, the compiler does a search for the function
prototype in same class.
Only when search fails, the compiler decides to go up the class hierarchy to look for the function
prototype in other classes.

30
In the given example, the display() function of the class XYZ is virtually hidden by the display() function
of the derived class ABC.
Now, let us consider the same example with a slight modification in the main() function.
int main()
{
XYZ x1;
x1.display();
retrun 0;
}

Here, the overridden function of the base class will be called.

Q: Can be called the overridden base class function with respect to derived class
object?
Ans: Yes, by using the scope resolution operator.
int main()
{
ABC a1;
a1.XYZ :: display();
retrun 0;
}

Note: But the overriding function cannot be called with respect to the base class
object.
int main()
{
XYZ x1;
x1.ABC : : display(); //Error
retrun 0;
}

31
Let us look another example, where an overridden function is called within an
overriding function using scope resolution operator.

#include<iostream>
using namespace std;
class XYZ
{
public:
void display() //overridden function
{
cout<<"I am in class XYZ"<<endl;
}
};

class ABC: public XYZ


{
public:
void display() //overriding function
{
XYZ::display(); //calling overridden function
cout<<"I am in class ABC"<<endl;
}
};

int main()
{
ABC a1;
a1.display();
return 0;
}

32
Example 1:
#include<iostream>
using namespace std;
class Person
{
int id;
char name[100];
public:
void set_data()
{
cout<<"Enter the Id:";
cin>>id;
fflush(stdin);
cout<<"Enter the Name:";
cin.get(name,100);
}
void display()
{
cout<<endl<<id<<"\t"<<name;
}
};

class Student: private Person


{
char course[50];
int fee;
public:
void set_data()
{
Person::set_data();
cout<<"Enter the Course Name:";
fflush(stdin);
cin.getline(course,50);
cout<<"Enter the Course Fee:";
cin>>fee;
}
void display()
{
Person::display();
cout<<"t"<<course<<"\t"<<fee;
}
};

main()
{
Student s;
s.set_data();
s.display();
return 0;
}

33
Example 2:
#include<iostream>
#include<string.h>
using namespace std;
class Person
{
int id;
char name[100];
public:
void set_data(int id,char n[])
{
this->id=id;
strcpy(this->name,n);
}
void display()
{
cout<<endl<<id<<"\t"<<name;
}
};

class Student: private Person


{
char course[50];
int fee;
public:
void set_data(int id,char n[],char c[],int f)
{
Person::set_data(id,n);
strcpy(course,c);
fee=f;
}
void display()
{
Person::display();
cout<<"t"<<course<<"\t"<<fee;
}
};

main()
{
Student s;
s.set_data(1001,"Manjeet kumar","Ph.D",2000);
s.display();
return 0;
}

34
Constructor in inheritance in C++

Example: Demonstrate the default constructor in single inheritance.


#include<iostream>
using namespace std;
class Person
{
int id;
char name[100];
protected:
Person()
{
cout<<"Enter the Id:";
cin>>id;
cout<<"Enter the Name:";
cin>>name;
}

void display()
{
cout<<endl<<id<<"\t"<<name;
}
};

class Student:public Person


{
char course[100];
int fee;
public:
Student():Person()
{
cout<<"Enter the course Name:";
fflush(stdin);
cin.getline(course,100);
cout<<"Enter the course Fee";
cin>>fee;
}

void display()
{
Person::display();
cout<<"\t"<<course<<"\t"<<fee;
}

};

main()
{
Student s;
s.display();
}

35
Example: Demonstrate the parameterized constructor in single inheritance.

#include<iostream>
#include<string.h>
using namespace std;
class Person
{
int id;
char name[100];
protected:
Person(int id,char name[])
{
this->id=id;
strcpy(this->name,name);

void display()
{
cout<<endl<<id<<"\t"<<name;
}
};

class Student: public Person


{
char course[100];
int fee;
public:
Student(int id,char name[],char cn[],int fee):Person(id,name)
{
strcpy(course,cn);
this->fee=fee;
}

void display()
{
Person::display();
cout<<"\t"<<course<<"\t"<<fee;
}

};

main()
{
Student s(1001,"Manjeet","Ph.D",39333);
s.display();
return 0;
}

36
Example: Demonstrate the parameterized constructor in Multiple inheritances.

#include<iostream>
using namespace std;
class A
{
protected:
int a;

A(int x)
{
a=x;
}
};

class B
{
protected:
int b;

B(int x)
{
b=x;
}
};

class C: public A, public B


{
int p;
public:
C(int x,int y):A(x),B(y)
{
p=a*b;

}
void display()
{
cout<<"Product="<<p;
}
};

main()
{
C _c(4,3);
_c.display();
return 0;
};

37
Advantages of Inheritance

 The most frequent use of inheritance is for deriving classes using existing classes, which provides
reusability. The existing classes remain unchanged. By reusability, the development time of the
software is reduced.

 The derived classes extend the properties of base classes to generate more dominant object.

 The same base classes can be used by a number of derived classes in class hierarchy.

 When a class is derived from more than one class all the derived classes have the same properties
as that of the base classes.

Disadvantages of Inheritance

 Inappropriate use of inheritance makes a program more complicated.

 Invoking member function using object create more compiler overheads.

 In class hierarchy various data members/elements remain unused.

Question: Make a class named Fruit with a data member to calculate the number of fruits in a basket.
Create two other class named Apple and Mango to calculate the number of apples and number of
mangoes in the basket. Print the number of fruits of each type and the total number of fruits in the basket.
#include<iostream>
using namespace std;

class Fruit {

protected:

static int nr_fruits;

public:

void printTotal() {

cout << "Total number of fruits in the basket: " << nr_fruits << endl;

}
};

int Fruit::nr_fruits;

class Mango : public Fruit {

38
int nr_mangoes;

public:

void getMango(int x) {

nr_mangoes = x;

cout << "The number of mangoes is " << nr_mangoes << " in the basket" << endl;

nr_fruits = nr_fruits + nr_mangoes;

}
};

class Apple : public Fruit {

int nr_apples;

public:

void getApple(int x) {

nr_apples = x;

cout << "The number of apples is " << nr_apples << " in the basket" << endl;

nr_fruits = nr_fruits + nr_apples;

}
};

int main()

Apple a1;

Mango m1;

a1.getApple(10);

a1.printTotal( );

m1.getMango(20);

m1.printTotal( );

return 0;

39
#include<iostream>
using namespace std;

class Mangoes{
public:
int nMango;
Mangoes(){
cout<<"No. of mangoes:";
cin>>nMango;
}
};

class Apples{
public:
int nApple;
Apples(){
cout<<"No. of apples:";
cin>>nApple;
}
};

class Fruit : public Mangoes, Apples{


public:
int nFruits;
void cal_no_of_fruit(){
nFruits = nMango+nApple;
}
void display(){
cout<<"No. of fruit are "<<nFruits;

}
};

int main(){
Fruit f;
f.cal_no_of_fruit();
f.display();
return 0;
}

Question: Write a C++ program to create a class called STUDENT with data members Roll Number,
Name and Age. Using inheritance, create the classes UGSTUDENT and PGSTUDENT having fields
Semester, Fee and Stipend.
Enter the data for at least 5 students. Find the semester wise average age for all UG and PG students
separately.

40
Question: A class Student has Roll No, Branch, class Internal_exam has sub1marks, sub2 marks,
class External_exam has sub1marks and class Result has Total as data members. Write necessary
member functions to input and print data.
(i) Calculate Internal_exam and External_exam subtotals using their respective member
functions.
(ii) Class Result has a function to calculate Total=internal+ external subtotals.

Write a complete program to implement the hierarchy of the classes using virtual base class.

41

You might also like