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

lab8,9 oop

The document is a lab manual focused on multi-level and multiple inheritance in object-oriented programming, specifically using C++. It covers the definitions, syntax, and objectives of multi-level and multiple inheritance, along with practical tasks to implement these concepts through class hierarchies. Additionally, it introduces function overloading and overriding, providing examples and tasks to reinforce understanding of these programming principles.

Uploaded by

Ali Jatt
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views

lab8,9 oop

The document is a lab manual focused on multi-level and multiple inheritance in object-oriented programming, specifically using C++. It covers the definitions, syntax, and objectives of multi-level and multiple inheritance, along with practical tasks to implement these concepts through class hierarchies. Additionally, it introduces function overloading and overriding, providing examples and tasks to reinforce understanding of these programming principles.

Uploaded by

Ali Jatt
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 21

Lab Manual for Object-Oriented Programming

(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
};
...

There is no limitation on the number of levels in multi-level inheritance.

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
};

2. Objective of the Experiment


After completing this lab, the student should be able to:
 develop multiple level class hierarchies
 derive a child class from multiple base classes
 understand the advantages of multi-level inheritance and multiple inheritance

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

Figure 1: Class Hierarchies showing Multi-level and Multiple Inheritance

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:

Design a class named Staff that includes


 A data member named staffID
 A parameterized constructor to initialize staffID
 A getter function to get the value of staffID
Derive a class named Professor inherited from Staff class and contains
 Two additional data members i.e. departmentID and departmentName
 A parameterized constructor to initialize its own data fields along with the inherited data
field
 Two getter functions that return the departmentID and departmentName, respectively
Derive a class named VisitingProfessor inherited from class Professor and has
 A data field named no_of_courses
 A data field named salary_per_course
 A function named totalSalary that returns total payment for all courses (i.e.
no_of_courses * salary_per_course)
 A member function named display to show total salary of visiting professor

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;
}
};

// Derived class from Staff


class Professor : public Staff {
int departmentID;
string departmentName;

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;
}
};

// Derived class from Professor


class VisitingProfessor : public Professor {
int no_of_courses;
float salary_per_course;

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);

cout << "Staff ID: " << vp.getStaffID() << endl;


cout << "Department ID: " << vp.getDepartmentID() << endl;
cout << "Department Name: " << vp.getDepartmentName() << endl;
vp.display();

return 0;
}

5
TASK-2

Consider four classes named Animal, Mammal, Bird, and Bat.


 class Animal that includes the functionality of eating and breathing
 class Mammal derived from Animal class and has additional functionality of giving
birth but not hatching
 class Bird derived from Animal class and has specific functionality of flying
 class Bat derived from both Animal and Bird classes while inheriting the functionality of
both these classes

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;

// Bat has access to all functions


bat.eat();
bat.breathe();
bat.giveBirth();
bat.fly();

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;
}
};

// Derived Class for Current Account


class CurrentAccount : public BankAccount {
public:
CurrentAccount(int id, float initialBalance) : BankAccount(id, initialBalance) {}

void amountWithdrawn(float amount) {


if (balance - amount >= 5000) {
balance -= amount;
cout << "Rs. " << amount << " withdrawn from Current Account. New Balance: Rs. " <<
balance << endl;
} else {
cout << "Withdrawal denied! Minimum balance of Rs. 5000 must be maintained in
Current Account." << endl;
}
}

void amountDeposit(float amount) {


balance += amount;
cout << "Rs. " << amount << " deposited in Current Account. New Balance: Rs. " <<
balance << endl;

9
}
};

// Derived Class for Savings Account


class SavingsAccount : public BankAccount {
public:
SavingsAccount(int id, float initialBalance) : BankAccount(id, initialBalance) {}

void amountWithdrawn(float amount) {


if (balance - amount >= 10000) {
balance -= amount;
cout << "Rs. " << amount << " withdrawn from Savings Account. New Balance: Rs. " <<
balance << endl;
} else {
cout << "Withdrawal denied! Minimum balance of Rs. 10000 must be maintained in
Savings Account." << endl;
}
}

void amountDeposit(float amount) {


balance += amount;
cout << "Rs. " << amount << " deposited in Savings Account. New Balance: Rs. " <<
balance << endl;
}
};

// Main function to test the classes


int main() {
// Current Account
CurrentAccount cAcc(101, 10000);
cout << "\n--- Current Account Transactions ---" << endl;
cAcc.balanceInquiry();
cAcc.amountWithdrawn(3000); // Valid
cAcc.amountWithdrawn(3000); // Invalid (would go below Rs. 5000)
cAcc.amountDeposit(2000);
cAcc.balanceInquiry();

// 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";
}
};

class Derived: public Base


{
public:
void myFunc()
{
cout<<"Derived Class’ Function";
}
void myFunc(int a)
{
cout<<"Derived Class’ Function with Parameter Value" <<a;
}
};

In the given example (above),


 At first, the class Derived shows function overloading while containing two functions
differ from each other in function signature (i.e. functions myFunc() and myFunc(int))

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.

5. Objective of the Experiment


After completing this lab, the student should be able to:
 Understand function overloading within a class
 Understand function overriding concerning inheritance class hierarchy
 Differentiate between function overloading and function redefining

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);
};

However, the same code with function overloading would be as

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;
}

int subtract(int a, int b) {


return a - b;
}

int multiply(int a, int b) {


return a * b;
}

int divide(int a, int b) {


if (b != 0)
return a / b;
else {
cout << "Error: Division by zero!" << endl;
return 0;
}
}

// --- Double operations ---


double add(double a, double b) {
return a + b;
}

double subtract(double a, double b) {


return a - b;
}

double multiply(double a, double 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;
}
}
};

// Main function to test the class


int main() {
Calculator calc;

int x = 10, y = 5;
double a = 7.5, b = 2.5;

cout << "--- Integer Operations ---" << endl;


cout << "Addition: " << calc.add(x, y) << endl;
cout << "Subtraction: " << calc.subtract(x, y) << endl;
cout << "Multiplication: " << calc.multiply(x, y) << endl;
cout << "Division: " << calc.divide(x, y) << endl;

cout << "\n--- Double Operations ---" << endl;


cout << "Addition: " << calc.add(a, b) << endl;
cout << "Subtraction: " << calc.subtract(a, b) << endl;
cout << "Multiplication: " << calc.multiply(a, b) << endl;
cout << "Division: " << calc.divide(a, b) << endl;

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;
}
};

// Derived class: Herbivore


class Herbivore : public Animal {
17
public:
void eat(string food) override {
cout << "Herbivore prefers to eat " << food << "." << endl;
}
};

// Derived class: Carnivore


class Carnivore : public Animal {
public:
void eat(string food) override {
cout << "Carnivore loves eating " << food << "." << endl;
}
};

// Derived class: Omnivore


class Omnivore : public Animal {
public:
void eat(string food) override {
cout << "Omnivore eats both plants and meat like " << food << "." << endl;
}
};
int main() {
Herbivore h;
Carnivore c;
Omnivore o;

cout << "--- Eating Preferences ---" << endl;


h.eat("grass");
c.eat("meat");
o.eat("berries and chicken");

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;

// Base class Shape


class Shape {
protected:
string ShapeName;
int area;

public:
// Default constructor
Shape() : ShapeName("Unknown"), area(0) {}

19
// Parameterized constructor
Shape(string name, int a) : ShapeName(name), area(a) {}

// Virtual function for polymorphic behavior


virtual void displayarea() {
cout << "Shape: " << ShapeName << ", Area: " << area << endl;
}
};

// Derived class Circle


class Circle : public Shape {
public:
Circle(string name, int a) : Shape(name, a) {}

void displayarea() override {


cout << "Circle Name: " << ShapeName << ", Area: " << area << endl;
}
};

// Derived class Polygon


class Polygon : public Shape {
public:
Polygon(string name, int a) : Shape(name, a) {}

void displayarea() override {


cout << "Polygon Name: " << ShapeName << ", Area: " << area << endl;
}
};

// Main function
int main() {
Circle c("Circle1", 314);
Polygon p("Hexagon", 300);

// Base class references


Shape* shape1 = &c;
Shape* shape2 = &p;

cout << "--- Displaying Area Using Base Class References ---" << endl;
shape1->displayarea(); // Calls Circle's displayarea
shape2->displayarea(); // Calls Polygon's displayarea

return 0;
}

20
21

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy