lab8,9 oop
lab8,9 oop
(LAB-08)
Multi-level and Multiple Inheritance
1
Lab 8: Multi-level and Multiple Inheritance
1. Introduction
In the previous labs i.e. in [Lab 06] and [Lab 07], you have already learned that the inheritance in
object-oriented programming (OOP) is the ability to transfer attributes and behaviors from
base/parent class(es) to derive/child class(es). As a next step, it is essential to learn the types of
inheritance on the basis of class hierarchies. Following different class hierarchies, inheritance in
OOP can be categorized as
Single Inheritance: a single child class derived from a single base class
Hierarchical Inheritance: multiple child classes derived from a single base class
Multi-level Inheritance: a single derived class inherited from another derived class
Multiple Inheritance: a single derived class inherited from more than one base classes
Hybrid Inheritance: any legal combination of more than one type of inheritance
In particular, the main focus of this lab is concerned with the understanding of multi-level and
multiple inheritance. Multi-level represents the scenario of inheriting attributes and behavior of a
class that is already inheriting attributes and behaviors from other class(es). The syntax of
writing C++ code to implement multi-level class hierarchy is given as under:
class X
{
// code statements go here
};
class Y: public X
{
//code statements go here
};
class Z: public Y
{
//code statements go here
};
...
Multiple Inheritance represents where a single class inherits attributes and behaviors from more
than one class. The syntax to write C++ code for multiple inheritance is given as under:
class X
{
// code statements go here
};
class Y
{
//code statements go here
2
};
class Z: public X, public Y
{
//code statements go here
};
3. Concept Map
Inheritance is one of the most important building blocks of OOP. The concept of reusable classes
is helpful to manage objects because occasionally it happens that a class may have some features
that it can derive from already existing class(es). Hence, with inheritance, it is sometimes crucial
to build multi-level class hierarchies or to derive class(es) from multiple existing classes. To
grasp the concept and need of multi-level and multiple inheritance, consider the following class
hierarchy
A person can be an employee or a student. An employee may have rights of admin officer or of
academic officer. These class hierarchies represent multi-level inheritance. However, a Dean or
Head of Department (HOD) may have rights to modify the status already defined by an admin or
academic officer. This type of relationship between classes is an example of multiple inheritance.
C++ facilitates users while supporting the implementation of both multi-level and multiple
inheritance. There is no limitation on the number of levels in multi-level inheritance and there is
no limitation on the number of parent classes from which a child can be derived. Nevertheless, as
a good practice, it is recommended to restrict levels and number of base classes to two in multi-
level and multiple inheritance.
3
LAB TASKS
TASK 1:
Draw UML diagram for each class and show inheritance relationship between these classes.
illustrate the implementation of these classes in C++.
CODE:
#include <iostream>
#include <string>
using namespace std;
// Base class
class Staff {
int staffID;
public:
Staff(int id) {
staffID = id;
}
int getStaffID() {
return staffID;
}
};
4
public:
Professor(int staff_id, int dept_id, string dept_name) : Staff(staff_id) {
departmentID = dept_id;
departmentName = dept_name;
}
int getDepartmentID() {
return departmentID;
}
string getDepartmentName() {
return departmentName;
}
};
public:
VisitingProfessor(int staff_id, int dept_id, string dept_name, int courses, float salary)
: Professor(staff_id, dept_id, dept_name) {
no_of_courses = courses;
salary_per_course = salary;
}
float totalSalary() {
return no_of_courses * salary_per_course;
}
void display() {
cout << "Total Salary of Visiting Professor: " << totalSalary() << endl;
}
};
// Example usage
int main() {
VisitingProfessor vp(1001, 10, "Computer Science", 3, 25000.5);
return 0;
}
5
TASK-2
Draw UML diagram for each class and show inheritance relationship between these classes.
Moreover, illustrate the implementation of these classes in C++.
CODE:
#include <iostream>
using namespace std;
// Base Class
class Animal {
public:
void eat() {
cout << "Animal eats food." << endl;
}
void breathe() {
cout << "Animal breathes air." << endl;
}
};
6
// Derived Class
class Mammal : virtual public Animal {
public:
void giveBirth() {
cout << "Mammal gives birth to live young." << endl;
}
};
// Derived Class
class Bird : virtual public Animal {
public:
void fly() {
cout << "Bird flies in the sky." << endl;
}
};
// Multiple Inheritance
class Bat : public Mammal, public Bird {
// Inherits all functionalities from Mammal and Bird
};
int main() {
Bat bat;
return 0;
}
7
TASK 3
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
o While withdrawing from current account, the minimum balance should not
decrease Rs. 5000
o While withdrawing from savings account, the minimum balance should not
decrease Rs. 10,000
amountDeposit(amount) to deposit amount in the account
8
In the main() function, create instances of derived classes (i.e. CurrentAccount and
SavingsAccount) and invoke their respective functions to test their working.
CODE:
#include <iostream>
using namespace std;
// Base Class
class BankAccount {
protected:
int accountID;
float balance;
public:
BankAccount(int id, float initialBalance) {
accountID = id;
balance = initialBalance;
}
void balanceInquiry() {
cout << "Account ID: " << accountID << ", Current Balance: Rs. " << balance << endl;
}
};
9
}
};
// Savings Account
SavingsAccount sAcc(202, 15000);
cout << "\n--- Savings Account Transactions ---" << endl;
sAcc.balanceInquiry();
sAcc.amountWithdrawn(4000); // Valid
sAcc.amountWithdrawn(2000); // Invalid (would go below Rs. 10000)
sAcc.amountDeposit(5000);
sAcc.balanceInquiry();
10
return 0;
}
11
Lab Manual for Object-Oriented Programming
(LAB-09)
Reusability III
Function Overloading and Function Overriding
12
Lab 9: Function Overloading and Function Overriding
4. Introduction
Earlier in Lab-08, you have already studied that a sub/derived class is able to access all non-
private data members and member functions of the base/parent class. Moreover, besides
inheriting attributes and behaviors from base class(es), the derived class also contains its own
data members and member functions.
Function overloading is the availability of various functions within a class that differ from each
other in function signature i.e. various functions share same name with different parameter types
or number of parameters. Inheritance is not necessarily required to overload functions within a
program.
On the other hand, in function overriding, there must exists inheritance relationship between
classes (i.e. base and derived) and functions’ signature are also required to be same in both
parent and child class(es). However, derived class(es) redefine function(s) having signature
similar to base class’s function(s).
Following code provides an example where both concepts (function overloading and overriding)
have been elaborated:
class Base
{
protected:
void myFunc()
{
cout<<"Base Class’ Function";
}
};
13
Secondly, it also shows function overriding as it holds two function implementations with
same signature (i.e. besides myFunc() of its own, it also contains myFunc() inherited from
the Base class.
6. Concept Map
Function overloading and function overriding are the two key concepts of a number of modern
computer programming languages.
Overloaded functions provide specific functionalities while taking into account the type/number
of parameter(s) they receive and the fundamental advantage is the cleanliness of code. For
example, in the absence of overloading, a computer program may have several functions with
different names to calculate the area of a geometric shape as shown below:
class GeometricShape{
public:
int squareArea(int sideLength);
int reactangleArea(int length, int width);
int triangleArea(int side1, int side2, int side3);
};
class GeometricShape{
public:
int area(int sideLength);
int area(int length, int width);
int area(int side1, int side2, int side3);
};
On the other hand, function overriding is the ability of redefining a specific behavior (function)
of a base class within derived class(es). Besides the provisioning of a specific modified
implementation of a base class function, function overriding is used to perform runtime
polymorphism.
14
LAB TASKS
Task-1
Consider a class named Calculator with typical four specific functionalities i.e. addition,
subtraction, multiplication, and division. Implement these functionalities as four functions with
two parameters. It is also required to overload all these functions for int and double data types.
In the main function, create an object of class Calculator and invoke its member functions while
passing parameters of int and double type.
#include <iostream>
using namespace std;
class Calculator {
public:
// --- Integer operations ---
int add(int a, int b) {
return a + b;
}
15
double divide(double a, double b) {
if (b != 0.0)
return a / b;
else {
cout << "Error: Division by zero!" << endl;
return 0.0;
}
}
};
int x = 10, y = 5;
double a = 7.5, b = 2.5;
return 0;
}
16
TASK-2
Consider a class named Animal having typical function named eat that accepts a parameter of
type string. Three classes i.e. Herbivore, Carnivore, and Omnivore have been inherited from
Animal class. All these classes i.e. Herbivore, Carnivore, and Omnivore must have their own
(overridden) eat function.
a) Draw UML diagram for each class and show inheritance relationship between these
classes.
b) Implement all these classes
c) In the main function, create instances of Herbivore, Carnivore, and Omnivore classes
and invoke eat function with appropriate string parameter to display the liking of that
animal in eating.
#include <iostream>
using namespace std;
// Base class
class Animal {
public:
virtual void eat(string food) {
cout << "Animal eats " << food << "." << endl;
}
};
return 0;
}
18
TASK 3
Consider a class Shape that contains
o A data member named as ShapeName of string type
o A data member named as areaof type int
o A member function displayarea()
Derive two classes named Circle and polygon from the class Shape that contain
o A parameterized constructor to initialize data members that they inherit from the
class Shape
In the main(), create instances of Shape Circle and Polygon classes. Invoke displayarea() with
shape object while passing references of Circle and Polygon instances.
#include <iostream>
using namespace std;
public:
// Default constructor
Shape() : ShapeName("Unknown"), area(0) {}
19
// Parameterized constructor
Shape(string name, int a) : ShapeName(name), area(a) {}
// Main function
int main() {
Circle c("Circle1", 314);
Polygon p("Hexagon", 300);
cout << "--- Displaying Area Using Base Class References ---" << endl;
shape1->displayarea(); // Calls Circle's displayarea
shape2->displayarea(); // Calls Polygon's displayarea
return 0;
}
20
21