Lab 05 Implementation of Inheritance, Function Overriding: Objectives
Lab 05 Implementation of Inheritance, Function Overriding: Objectives
function overriding
March 12, 2024, 08:00 am to 10:00 am
Instructor: Dr. M. Umar Khan
Instructions:
1. Lab Reports must be submitted in both hard and soft forms before the deadline.
2. The cover page of the assignment must clearly state the Name and Registration of the
student along with the title of the Lab.
3. For online submission use MS Team group of section BCE 2B.
4. All lab reports are assessed as per rubric defined in the course description file (CDF).
1. Objectives
To familiarize the students with various concepts and terminologies of inheritance in
Programming.
2. Outcome
After this lab the students should be able to declare the derived classes along with the
access of base class members. They should learn the purpose of protected Access
Specifier and working with derived class constructors. They should be familiar with
the use of overriding.
3. Introduction
3.1. Inheritance
Inheritance is a way of creating a new class by starting with an existing class and
adding new members. The new class can replace or extend the functionality of the
existing class.The existing class is called the base class and the new class is called
the derived class.
3.4. Overriding
Method overriding, in object oriented programming, is a language feature that
Page 1 of 8
allows a subclass or child class to provide a specific implementation of a method
that is already provided by one of its superclasses or parent classes. The
implementation in the subclass overrides (replaces) the implementation in the
superclass by providing a method that has same name, same parameters or
signature, and same return type as the method in the parent class. The version of a
method that is executed will be determined by the object that is used to invoke it.
If an object of a parent class is used to invoke the method, then the version in the
parent class will be executed, but if an object of the subclass is used to invoke the
method, then the version in the child class will be executed. Some languages allow
a programmer to prevent a method from being overridden.
4. Examples
4.1. This example will explain the method to specify the derived class.
#include<iostrea
m>
#include<conio.h
> using namespace
std;
public:
void setJ(int n); // function prototype
int mul(); // function prototype
{
num1 = n;
}
Page 2 of 8
return num1;
}
{
num2 = n;
}
{
cout<<"Result=";
return (num2 * getInt());
}
int main()
{
DerivedClass ob; //derived class object
return 0;
}
4.2.This example will explain the way to access the base class
members with derived class object.
#include<iostre
am> using
namespace
std;
public:
Page 3 of 8
Counter(int c) : count(c) //1-arg constructor
{ }
unsigned int get_count() const //return count
{ return count; }
Counter operator ++ () //incr count (prefix)
{ return Counter(++count); }
};
class CountDn : public Counter //derived class
{
public:
Counter operator -- () //decr count (prefix)
{ return Counter(--count); }
};
int main()
{
CountDn c1; //c1 of class
4.3. This example demonstrates that how we can use the concept of
Overriding.
#include<iostrea
m>
#include<conio.h
> using
namespace std;
class Stack {
protected: //NOTE: can't be private
enum { MAX = 3 }; //size of stack array
int st[MAX]; //stack: array of integers
int top; //index to top of stack
public:
Stack() //constructor
Page 4 of 8
{
top = -1;
}
void push(int var)
{
st[++top] = var; //put number on stack
}
int pop()
{
return st[top--]; //take number off stack
}
};
class Stack2 : public Stack
{ public:
void push(int var)
{ //put number on stack
if(top >= MAX-1) //error if stack full
{
cout << "\nError: stack is
full"; exit(1);
}
Stack::push(var); //call push() in Stack class
}
int pop() //take number off stack
{
if(top < 0) //error if stack empty
{ cout << "\nError: stack is
empty\n"; exit(1);
}
return Stack::pop(); //call pop() in Stack class
}
};
int main()
{
Stack2 s1;
s1.push(11); //push some values onto
stack s1.push(22);
s1.push(33);
cout << endl << s1.pop(); //pop some values from
Page 5 of 8
stack cout << endl << s1.pop();
cout << endl << s1.pop();
cout << endl << s1.pop(); //oops, popped one too
many... cout << endl;
system("paus
e"); getch();
return 0;
}
5. Lab Tasks
5.1. Imagine a publishing company that markets both book and audio-cassette
versions of its works. Create a class publication that stores the title and price
of a publication.
a. from this class derive two classes:
i. book, which adds a page count and
ii. tape, which adds a playing time in minutes.
iii. each of these three classes should have getdata() function to get its data
from the user at the keyboard and a putdata() function to display its data.
b. Write a main() program to test the book and tape class by creating instances
of them, asking the user to fill in their data with getdata() and then displaying
the data with putdata().
5.2. Write a class Person that has attributes of id, name and address. It has a
constructor to initialize, a member function to input and a member function
to display data members. Create another class Student that inherits Person
class. It has additional attributes of rollnumber and marks. It also has
member function to input and display its data members.
5.3. Write a base class Computer that contains data members of wordsize(in
bits), memorysize (in megabytes), storagesize (in megabytes) and speed (in
megahertz). Derive a Laptop class that is a kind of computer but also
specifies the object9s length, width, height, and weight. Member functions
for both classes should include a default constructor, a constructor to
inialize all components and a function to display data members.
6. Home Tasks
6.1. Write a program having a base class Student with data members rollno,
name and Class define a member functions getdata() to input values and
another function putdata() to display all values. A class Test is derived from
class Student with data members T1marks, T2marks, T3marks, Sessional1,
Page 6 of 8
Sessional2, Assignment and Final. Also make a function getmarks() to enter
marks for all variables except Final and also make a function putmarks() to
display result. Make a function Finalresult() to calculate value for final
variable using other marks. Then display the student result along with student
data.
6.2. Write a program that declares two classes. The parent class is called
Simple that has two data members num1 and num2 to store two
numbers. It also has four member functions.
• The add() function adds two numbers and displays the result.
• The sub() function subtracts two numbers and displays the result.
• The mul() function multiplies two numbers and displays the result.
• The div() function divides two numbers and displays the result.
The child class is called Complex that overrides all four functions. Each function
in the child class checks the value of data members. It calls the corresponding
member function in the parent class if the values are greater than 0. Otherwise it
displays error message.
6.3. An electricity board charges the following rates to domestic users to
discourage large consumption of energy.
• For the first 100 units − 50 P per unit
• Beyond 100 units − 60 P per unit
If the total cost is more than Rs.250.00 then an additional surcharge of 15% is
added on the difference. Define a class Electricity in which the function Bill
computes the cost. Define a derived class More_Electricity and override Bill to
add the surcharge.
Page 7 of 8
shipping the package. Package's calculateCost() function should determine
the cost by multiplying the weight by the cost per ounce. Derived class
TwoDayPackage should inherit the functionality of base class Package, but
also include a data member that represents a flat fee that the shipping
company charges for two-day-delivery service. TwoDayPackage's
constructor should receive a value to initialize this data member. TwoDayPackage
should redefine member function calculateCost() so that it computes the shipping
cost by adding the flat fee to the weight-based cost calculated by base class
Package's calculateCost() function. Class OvernightPackage should inherit
directly from class Package and contain an additional data member representing
an additional fee per ounce charged for overnight-delivery service.
OvernightPackage should redefine member function calculateCost() so that it adds
the additional fee per ounce to the standard cost per ounce before calculating the
shipping cost. Write a test program that creates objects of each type of Package
and tests member function calculateCost().
7. References
[i]Object-Oriented Programming in C++, By Robert
Lafore [ii]C++ How to Program, By Deitel & Deitel
Page 8 of 8