0% found this document useful (0 votes)
5 views

Lab Manual 07 -Inheritance and Its Types (1)

Uploaded by

sanaindesign
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Lab Manual 07 -Inheritance and Its Types (1)

Uploaded by

sanaindesign
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 21

Lab Manual: Object Oriented Programming

University of Management and Technology,


Lahore Campus

Lab- 07 Manual
Lab Instructor: Riaz Ahmad
Department of Computer Science
Email: [email protected]
Lab: 07 Table of Contents
Following are the topics that we will cover in this Lab.
 Introduction
 Objective of the Experiment
 Concept Map
 Inheritance
 Generalization
 Specialization
 Constructor and Destructor
 Examples
 Different types of inheritance
 Inheritance types implementation Examples
 Practice Tasks

Department of Computer Science, UMT, Lahore. 1 Riaz Ahmad


Lab Manual: Object Oriented Programming
Lab Description:
This lab is designed to understand the inheritance and its types.
Lab Rubrics:
Identify the objects &
Individual/Team
Problem their relationships to Design/ Development
Areas work towards the
Understanding build object-oriented of Solutions
Assessed Assigned task
solution
(CLO 1) (CLO 2) (CLO 3) (CLO 4)
Not able to No able to identify Not able to Model a Wasn't able to
Poor understand objects and their solution for a given explain
Problem relationships problem experimental work

Modeled an average
Able to partially Partially able to identify Not completely able
solution for a given
Average understand the objects and their to explain
problem using object-
problem relationships experimental work
oriented principles
Able to
Thoroughly Identify the Modeled a proper explain/defend the
Fully Understand objects & their solution for a given assigned task and all
Very Good
the problem relationships to build problem using object- the questions have
object-oriented solution oriented principles been answered
correctly

Objective:

To cover

 Inheritance
 Single Inheritance
 Multiple Inheritance
 Multi-Level Inheritance
 Hybrid Inheritance
 Hierarchical Inheritance

Scope:

The student should know the following at the end of this lab:
 Problem understanding
 Problem Solving

Theory: [CLO 1]

Introduction [CLO 1]

Department of Computer Science, UMT, Lahore. 2 Riaz Ahmad


Lab Manual: Object Oriented Programming
Object-Oriented Programming (OOP) strongly supports reusability and in this regard, inheritance
is perhaps the strongest way of reusing the features of a class i.e. attributes (data member) and
behaviors (functions). Following the OOP paradigm, C++ allows the inheritance among classes
so that the characteristic(s) of one class is/are inherited by the other class(es). Hence, you can say
that the derived classes receive some their attributes from which the derived class is inherited. A
major advantage of inheritance is that it allows the reusability of code. Hence, the programmer
can simply create new (child) class(es) by using other (parent) class(es).

While considering the advantages of commonality between classes, in C++, you are able to
manage your classes in a way that a class (child/sub class) can extend the functionality by
inheriting the attributes and behaviors of an existing class commonly known as base/super class.
In simple words, you can define a class with certain data fields and/or member functions and
then identify other class(es) that can share these data fields and functions. In typical C++
inheritance, a class or classes known as derived class(es), subclass(es) or child class(es) is/are
able to inherit certain attributes and behavior of pre-existing class(es) that are known as base
class(es), superclass(es), or parent class(es). In practice, base classes are more general while
derived classes are specialized version of base classes and due to this reason, it is said that
inheritance maintains generalization and specialization. With inheritance, you can greatly
save the time and lessen the effort to write duplicate code.

Concerning inheritance syntax in C++, if you have a base class named person inherited by a
derived class named student then you have to write code in the following way.

In case of derived class’s object instantiation, default/no-argument constructor for the base
class(es) are automatically called first and are followed by calling derived class’s constructors.
If base class(es) is/are without default/no-argument constructor, then it is must to call explicitly
any base class’s constructor even if there is no need to call a constructor.

Department of Computer Science, UMT, Lahore. 3 Riaz Ahmad


Lab Manual: Object Oriented Programming

Objective of the Experiment


After completing this lab, the student should be able to:
 get basic understanding of inheritance concept in OOP
 derive class(es) from other base class(es) through inheritance
 understand the constructor and destructor chaining in inheritance hierarchy
 know how to invoke the base class’s constructors within derived class(es)
Concept Map
Inheritance is one of the most important building blocks of OOP. The concept of reusable classes
is helpful to manage objects. You can create new classes (derived classes) that are able to inherit
certain attributes and behavior of their ancestor or base class(es). Prior to working with
inheritance, it is important to consider the following aspects of inheritance.

 Inheritance represents “is-a” relationship in OOP i.e. any specific object is a type of a
more general class of object. For example, Train is a type of Vehicle
 By design, a derived class should inherit all attributes and behaviors of its base class(es)
 While declaring its own data fields a derived class can extend the features of its base
class(es)
 While defining new functionality, a derived class can modify the behavior provided by
the base class(es)

Inheritance in OOP saves a lot of work and time. You can save additional work as some of the
object definitions(class) already exists. Time saving is due to the reason that much of the code
has already been written and tested.

Department of Computer Science, UMT, Lahore. 4 Riaz Ahmad


Lab Manual: Object Oriented Programming

If a class B inherits from class A then it contains all the characteristics (information structure and behavior
of class A.
The parent class is called base class and the child class is called derived class Besides inherited
characteristics, derived class may have its own unique characteristics

Examples:

Inheritance – “IS A” or “IS A KIND OF” Relationship

Each derived class is a kind of its base class

Here,
Student IS A Person
Teacher IS A Person
Doctor IS A Person

Here,
Circle IS A Shape
Line IS A Shape
Triangle IS A Shape

Department of Computer Science, UMT, Lahore. 5 Riaz Ahmad


Lab Manual: Object Oriented Programming

Generalization
In OO models, some classes may have common characteristics. We extract these features into a
new class and inherit original classes from this new class. There are many objects with common
characteristics in object model. The common characteristics (attributes and behaviour) of all
these objects are combined in a single general class. Base class encapsulates the idea of
commonality of derived classes. Base class is general class representing common behaviour of
all derived classes.
This concept is known as Generalization.
It reduces the redundancy and gives us reusability, using generalization our solution becomes less
complex.
In generalization there should be “Is a Kind of Relationship” (also called “Is A relationship”)
between base and child classes.

Examples: Line,Circle,Triangle

Common attributes
Color vertices
Common behaviour
Set Color, Move

Department of Computer Science, UMT, Lahore. 6 Riaz Ahmad


Lab Manual: Object Oriented Programming

Example: Student, Doctor and Teacher

Common attributes, Common behaviour


Name, age, gender Eat, Walk

Department of Computer Science, UMT, Lahore. 7 Riaz Ahmad


Lab Manual: Object Oriented Programming
Sub-typing & Specialization
We want to add a new class to an existing model. We have developed an existing class hierarchy Find an existing class that
already implements some of the desired state and behavior Inherit the new class from this class and add unique behavior to
the new Class.

Sub-typing (Extension)
Sub-typing means that derived class is behaviorally compatible with the base class Derived class has all the
characteristics of base class plus some extra characteristics Behaviorally compatible means that base class can be
replaced by the derived class.

Sub-typing (Extension) – Example

1. Circle is extending the behavior of shape, it is extending attributes of shape by adding


radius similarly it is extending behavior of shape by adding compute Circumference
and compute Area.
2. Student has two extra attributes program and studyYear Similarly it has extended
behavior by adding study and takeExam.

Note: Every object of derived class has an anonymous object of base class

Department of Computer Science, UMT, Lahore. 8 Riaz Ahmad


Lab Manual: Object Oriented Programming

Constructors
 The anonymous object of base class must be initialized using constructor of base class
 When a derived class object is created the constructor of base class is executed before
the constructor of derived class

Example: Check the Behavior of Constructor and Destructor [CLO 2]


#include class Derived:public
Parent{ public:
<iostream> using Derived(){
cout<<"\nI am Derived class Constructor";
namespace std; }
~Derived(){
class Parent{ cout<<"\n\nI am Derived class Destructor";
}
public: };
Parent(){
cout<<"\nI am Parent class Constructor"; int main()
{
}
~Parent(){ Derived
cout<<"\nI am Parent class Destructor\n"; d; return
} 0;
}
};

Note:
The base class’s constructor is called before the derived class’s constructor. The destructors are
called in reverse order, with the derived class’s destructor being called first.

Department of Computer Science, UMT, Lahore. 9 Riaz Ahmad


Lab Manual: Object Oriented Programming

 If default constructor of base class does not exist then the compiler will try to generate a
default constructor for base class and execute it before executing constructor of derived
class
 If the user has given only an overloaded constructor for base class, the compiler will not
generate default constructor for base class

Example:

class Parent{
public:
Parent(int i)
{}
};
class Child : public
Parent{ public:
Child(){}
} Child_Object; //ERROR

Default constructor:
Default constructor is such constructor which either has no parameter or if it has some parameters these
have default values. The benefit of default constructor is that it can be used to create class object without
passing any argument.

Implicit Default constructor:


Compiler generates implicit default constructor for any class in case we have not given any constructor for
the class.

Explicit Default constructor:


If user has given constructor for any class without any arguments or with all arguments with default
values then it is also default constructor according to definition but it is explicit (user defined) default
constructor.
Now if a base class has only non-default constructor (constructor with parameters without default values),
then when we will create object of any class derived from this base class compiler will not be able to call
base class constructor as base class has no default constructor (constructor that can be called without
giving any parameters) so compiler will generate error.

We can avoid this error by calling base class non-default constructor in derived class
constructor initializer list by ourself.

Department of Computer Science, UMT, Lahore. 10 Riaz Ahmad


Lab Manual: Object Oriented Programming

Base Class Initializer


• C++ has provided a mechanism to explicitly call a constructor of
base class from derived class
• The syntax is similar to member initializer and is referred as
base-class initialization

Examples:
class
Parent{ pub
lic:
Parent(int i){…};
};

class Child : public


Parent{ public:
Child(int i): Parent(i)
{…}
};
class
Parent{ pub
lic:
Parent()
{
cout << “Parent Constructor...”;}
...
};

class Child : public


Parent{ public:
Child():Parent()
{cout << “Child Constructor...”;}
...
};

Base Class Initializer


• User can provide base class initializer and member initializer simultaneously
class
Parent{ pu
blic:
Parent()
{…}
};
class Child : public
Parent{ int member;
public:
Child():member(0), Parent()
{…}
};

Department of Computer Science, UMT, Lahore. 11 Riaz Ahmad


Lab Manual: Object Oriented Programming
Base Class Initializer
 The base class initializer can be written after member initializer for derived Class
 The base class constructor is executed before the initialization of data members of derived class.
Initializing Members
 Derived class can only initialize members of base class using overloaded constructors
 Derived class cannot initialize the public data member of base class using member
initialization list.

class
Person{ pu
blic:
int age;
char *name;
...
public:
Person();
};
Example
class Student: public
Person{ private:
int semester;
...
public:
Student(int a):age(a) //error
{
}
};

Reason
• It will be an assignment not an initialization

Department of Computer Science, UMT, Lahore. 12 Riaz Ahmad


Lab Manual: Object Oriented Programming

Different Types of Inheritance

Department of Computer Science, UMT, Lahore. 13 Riaz Ahmad


Lab Manual: Object Oriented Programming
Example: Implementation of Single level Inheritance [CLO 2]
#include<iostream> class B:public A
using namespace std; {
int b;
class A public:
{ B(int j,int i):A(i)
int a; {
public: b=j;
A(int i) }
{ void show()
a=i; {
} cout<<"\nThe Value of b:"<<b;
void Display() }
{ };
cout<<"\nThe value of a:"<<a;
}
};

int main()
{
B b(4,5);
cout<<" B class";
b.Display();
b.show();

return 0;
}

Department of Computer Science, UMT, Lahore. 14 Riaz Ahmad


Lab Manual: Object Oriented Programming

Example: Implementation of Multilevel Inheritance [CLO 2]


#include<iostream class B:public A class
> using namespace { C:public B{
std; int b; int c;
publi public:
class A c: C()
{ B() {c
int a; { =0;
b=0; }
public:
A() } void setc(int
{ void setb(int i){ c=i;
a=0; i){ b=i; }
} } int
void seta(int int get_c()const{
i){ a=i; getb()const{ r return c;
} eturn b; }
int } void print(){
geta()const{ r void show() this-
eturn a; { >show();
} Display(); cout<<"\n The Value of
void Display() cout<<"\nThe Value of c:"<<get_c();
{ b:"<<getb();
}
cout<<"\nThe value of }
};
a:"<<geta(); };
}
};
int main()
{
C c;
c.seta(4)
;
c.setb(3);
c.setc(2);
c.print();

return 0;
}

Department of Computer Science, UMT, Lahore. 15 Riaz Ahmad


Lab Manual: Object Oriented Programming
Example: Implementation of Hierarchal Inheritance [CLO 2]

#include<iostream> class B:public A class C:public A


using namespace std; { {
int b; int c,d;
class A
{ public: public:
int a; B(int j,int i):A(i) C(int j,int k,int i):A(i)
public: { {
A(int i) b=j; c=j;
{ } d=k;
a=i; void show() }
} { void show()
void Display() cout<<"\nThe Value of {
b:"<<b;
{ cout<<"\nThe Value of
c:"<<c;
} cout<<"\nThe Value of
d:"<<d;
cout<<"\nThe value of a:"<<a; };
} }
}; };
int main()
{
B b(4,5);
C c(8,7,9);

cout<<"\nThe B
class"; b.Display();
b.show();

cout<<" \n\n C
class"; c.Display();
c.show()
; return
0;
}

Note: Multiple and Hybrid inheritance will be implemented in coming session.

Department of Computer Science, UMT, Lahore. 16 Riaz Ahmad


Lab Manual: Object Oriented Programming
Multiple Inheritance:

#include<iostream> class C:public A,B


using namespace std; {
int c,d;
class A
{ public:
int a; C(int j,int k,int i,int L):A(i),B(L)
public: {
A(int i) c=j;
{ d=k
a=i; ;
} }
void Display() void Display()
{ {
A::Display();
cout<<"\nThe value of a:"<<a; B::Display();
} cout<<"\nThe Value of c:"<<c; cout<<"\
}; nThe Value of d:"<<d;
class B
{ }
int b; };
public:
B(int j) int main()
{ {
b=j;
} C c(8,7,9,10);
void Display() c.Display();
{
cout<<"\nThe Value of b:"<<b; return 0;
} }
};

Department of Computer Science, UMT, Lahore. 17 Riaz Ahmad


Lab Manual: Object Oriented Programming

Hybrid Inheritance:

#include<iostream> class B:public A


using namespace std; {
int b;
class A
{ public:
int a; B(int j,int i):A(i)
public: {
A(int i) b=j;
{ }
a=i; void Display()
} {
void Display() A::Display();
{ cout<<"\nThe Value of b:"<<b;

cout<<"\nThe value of a:"<<a; }


} };
};

Department of Computer Science, UMT, Lahore. 18 Riaz Ahmad


Lab Manual: Object Oriented Programming

class C:public A class D:public B,C


{ {
int c; int d;

public: public:
C(int j,int i):A(i) D(int j,int k,int i,int l,int m):B(k,i),C(l,m)
{ {
c=j; d=j;
} }
void Display() void Display()
{ {
A::Display(); cout<<"\nData from B to A";
cout<<"\nThe Value of c:"<<c; B::Display();
cout<<"\n\nData from C to A";
} C::Display();
}; cout<<"\nThe Value of d:"<<d;

}
};
int main(){
D d(3,4,5,6,7);
d.Disp
lay();
} return
0;

Department of Computer Science, UMT, Lahore. 19 Riaz Ahmad


Lab Manual: Object Oriented Programming
Practice Tasks: [CLO 2, 3, 4]
This section will provide more practice exercises which you need to finish during the lab.
You need to finish the tasks in the required time.
Practice Task 1:
Consider a base class named Employee and its derived classes HourlyEmployee and
PermanentEmployee while taking into account the following criteria.

 Employee class has two data fields i.e. a name (of type string) and specific
empID (of type integer)
 Both classes (HourlyEmployee and PermanentEmployee) have an attribute
named hourlyIncome
 Both classes (HourlyEmployee and PermanentEmployee) have three-argument
constructor to initialize the hourlyIncome as well as data fields of the base class
 Class HourlyEmployee has a function named calculate_the_hourly_income to
calculate the income of an employee for the actual number of hours he or she
worked. One hour income is Rs. 150
 Similarly, PermanentEmployee class has function named calculate_the_income
to calculate the income of an employee that gets paid the salary for exact 240
hours, no matter how many actual hours he or she worked. Again, one hour
salary is Rs. 150.

Implement all class definitions with their respective constructors to initialize all data
members and functions to compute the total income of an employee. In the main()
function, create an instance of both classes (i.e. HourlyEmployee and
PermanentEmployee) and test the working of functions that calculate total income of
an employee.

Practical Task 02 [CLO 2, 3, 4]


Consider a class BankAccount that has
 Two attributes i.e. accountID and balance and
 A function named balanceInquiry() to get information about the current
amount in the account

Derive two classes from the BankAccount class i.e. CurrentAccount and the
SavingsAccount. Both classes (CurrentAccount and SavingsAccount) inherit all
attributes/behaviors from the BankAccount class. In addition, followings are
required to be the part of both classes

Appropriate constructors to initialize data fields of base class


 A function named amountWithdrawn(amount) to withdraw certain amount
while taken into account the following conditions
 While withdrawing from current account, the minimum balance should not
decrease Rs. 5000
 While withdrawing from savings account, the minimum balance should not
decrease Rs. 10,000

Department of Computer Science, UMT, Lahore. 20 Riaz Ahmad


Lab Manual: Object Oriented Programming
 amountDeposit(amount) to deposit amount in the account

In the main() function, create instances of derived classes (i.e.


CurrentAccount and SavingsAccount) and invoke their respective
functions to test their working.

Department of Computer Science, UMT, Lahore. 21 Riaz Ahmad

You might also like