OOP Lab-13,14a

Download as pdf or txt
Download as pdf or txt
You are on page 1of 14

UNIVERSITY OF ENGINEERING AND TECHNOLOGY, TAXILA

DEPARTMENT OF COMPUTER SCIENCE


http://web.uettaxila.edu.pk

CS-103 | Object Oriented Programming (Lab)

LAB Manual 13,14


Classes and Objects in C++

Instructor
Muhammad Faheem Saleem

Lab Manual: CS-103 (Object Orient Programming)


UNIVERSITY OF ENGINEERING AND TECHNOLOGY, TAXILA
DEPARTMENT OF COMPUTER SCIENCE
http://web.uettaxila.edu.pk

Topics: Polymorphism

Polymorphism is an important concept of object-oriented programming. It simply means more than


one form. When the same entity (function or object) behaves differently in different scenarios, it
is known as Polymorphism.

e.g the “ +” operator in c++ can perform two specific functions at two different scenarios i.e
when the “+” operator is used in numbers, it performs addition.
int a = 6;

int b = 6;
int sum = a + b; // sum =12

And the same “+” operator is used in the string, it performs concatenation.
string firstName = "Great ";

string lastName = "Learning";

// name = "Great Learning "


string name = firstName + lastName;

Lab Manual: CS-103 (Object Orient Programming)


UNIVERSITY OF ENGINEERING AND TECHNOLOGY, TAXILA
DEPARTMENT OF COMPUTER SCIENCE
http://web.uettaxila.edu.pk

A real-life example of polymorphism is a person who at the same time can have different
characteristics. Like a man at the same time is a father, a husband and an employee. So the same
person exhibits different behavior in different situations. This is called polymorphism.
Polymorphism is considered as one of the important features of Object-Oriented Programming.

Types:

We have two types of polymorphism:


1) Compile time Polymorphism – This is also known as static (or early) binding.
2) Runtime Polymorphism – This is also known as dynamic (or late) binding.

Compile-time polymorphism:
This type of polymorphism is achieved by function overloading or operator overloading.
Function Overloading: When there are multiple functions with the same name but different
parameters, then the functions are said to be overloaded. Functions can be overloaded by changing
the number of arguments or/and changing the type of arguments.
Example : C++ program to overload sum() function

#include <iostream>
using namespace std;

// Function with 2 int parameters


int sum(int num1, int num2) {
return num1 + num2;
}

// Function with 2 double parameters

Lab Manual: CS-103 (Object Orient Programming)


UNIVERSITY OF ENGINEERING AND TECHNOLOGY, TAXILA
DEPARTMENT OF COMPUTER SCIENCE
http://web.uettaxila.edu.pk

double sum(double num1, double num2) {


return num1 + num2;
}
// Function with 3 int parameters
int sum(int num1, int num2, int num3) {
return num1 + num2 + num3;
}

int main() {
// Call function with 2 int parameters
cout << "Sum 1 = " << sum(5, 6) << endl;

// Call function with 2 double parameters


cout << "Sum 2 = " << sum(5.5, 6.6) << endl;

// Call function with 3 int parameters cout


<< "Sum 3 = " << sum(5, 6, 7) << endl;

return 0; }
Output
Sum 1 = 11
Sum 2 = 12.1
Sum 3 = 18
Here, we have created 3 different sum() functions with different parameters (number/type of
parameters). And, based on the arguments passed during a function call, a particular sum() is called.
It's a compile-time polymorphism because the compiler knows which function to execute before
the program is compiled.

Lab Manual: CS-103 (Object Orient Programming)


UNIVERSITY OF ENGINEERING AND TECHNOLOGY, TAXILA
DEPARTMENT OF COMPUTER SCIENCE
http://web.uettaxila.edu.pk

Operator Overloading: C++ also provides the option to overload operators. For example, we can
make use of the addition operator (+) for string class to concatenate two strings. We know that the
task of this operator is to add two operands. So a single operator ‘+’, when placed between integer
operands, adds them and when placed between string operands, concatenates them.
Example: CPP program to illustrate Operator Overloading

Lab Manual: CS-103 (Object Orient Programming)


UNIVERSITY OF ENGINEERING AND TECHNOLOGY, TAXILA
DEPARTMENT OF COMPUTER SCIENCE
http://web.uettaxila.edu.pk

#include<iostream> using
namespace std;
class Complex {
private:
int real, imag;
public:
Complex(int r = 0, int i =0) {real = r; imag = i;}

// This is automatically called when '+' is used with between two Complex objects
Complex operator + (Complex const &obj) {
Complex res;
res.real = real + obj.real;
res.imag = imag + obj.imag;
return res;
}
void print() { cout << real << " + i" << imag << endl; }
};

int main()
{
Complex c1(10, 5), c2(2, 4);
Complex c3 = c1 + c2; // An example call to "operator+"
c3.print();
}

Output
12 + i9

Lab Manual: CS-103 (Object Orient Programming)


UNIVERSITY OF ENGINEERING AND TECHNOLOGY, TAXILA
DEPARTMENT OF COMPUTER SCIENCE
http://web.uettaxila.edu.pk

In the above example, the operator ‘+’ is overloaded. Usually, this operator is used to add two
numbers (integers or floating point numbers), but here the operator is made to perform the
addition of two imaginary or complex numbers. Lets us consider another example :

#include <iostream> using


namespace std;
class A
{
string x;
public:
A(){}
A(string i)
{
x=i;
}
void operator+(A);
void display();
};

void A:: operator+(A a)


{
string m = x+a.x;
cout<<"The result of the addition of two objects is : "<<m;

}
int main()
{
A a1("Welcome");
A a2("back");
a1+a2;
return 0;
}

Output
The result of the addition of two objects is: Welcomeback
This code defines a class A with a constructor that initializes a member variable x with a string
value. It also overloads the + operator as a member function to concatenate two A objects' x

Lab Manual: CS-103 (Object Orient Programming)


UNIVERSITY OF ENGINEERING AND TECHNOLOGY, TAXILA
DEPARTMENT OF COMPUTER SCIENCE
http://web.uettaxila.edu.pk

values and display the result. In the main() function, it creates two A objects, initializes them
with strings "Welcome" and "back" respectively, and then uses the overloaded + operator to
concatenate them together. Finally, it prints the concatenated string
Runtime Polymorphism
In a Runtime polymorphism, functions are called at the time the program execution. Hence, it is
known as late binding or dynamic binding.
a. Virtual Functions

A virtual function is a member function which is declared within a base class and is re-
defined (overridden) by a derived class. When you refer to a derived class object using a
pointer or a reference to the base class, you can call a virtual function for that object and
execute the derived class’s version of the function.

- Virtual functions ensure that the correct function is called for an object, regardless of the
type of reference (or pointer) used for function call.
- They are mainly used to achieve Runtime polymorphism
- Functions are declared with a virtual keyword in base class.
- The resolving of function call is done at runtime.

Rules for Virtual Functions

▪ Virtual functions cannot be static.


▪ A virtual function can be a friend function of another class.
▪ Virtual functions should be accessed using pointer or reference of base class type to achieve
runtime polymorphism.
▪ The prototype of virtual functions should be the same in the base as well as derived class.
▪ They are always defined in the base class and overridden in a derived class. It is not
mandatory for the derived class to override (or re-define the virtual function), in that case,
the base class version of the function is used.
▪ A class may have virtual destructor but it cannot have a virtual constructor.

Example : program to illustrate concept of Virtual Functions

#include<iostream>

Lab Manual: CS-103 (Object Orient Programming)


UNIVERSITY OF ENGINEERING AND TECHNOLOGY, TAXILA
DEPARTMENT OF COMPUTER SCIENCE
http://web.uettaxila.edu.pk

using namespace std;

class base { public:


virtual void print()
{
cout << "print base class\n";
}

void show()
{
cout << "show base class\n";
}
};

class derived : public base { public:


void print()
{
cout << "print derived class\n";
}

void show()
{
cout << "show derived class\n";
}
};

int main()
{
base *bptr;
derived d;
bptr = &d;

// Virtual function, binded at runtime


bptr->print();

// Non-virtual function, binded at compile time bptr->show();

return 0;
}

Lab Manual: CS-103 (Object Orient Programming)


UNIVERSITY OF ENGINEERING AND TECHNOLOGY, TAXILA
DEPARTMENT OF COMPUTER SCIENCE
http://web.uettaxila.edu.pk

Output:
print derived class
show base class

Virtual means existing in appearance but not in reality. When virtual functions are used, a
program that appears to be calling a function of one class may in reality be calling a
function of a different class.
Why are virtual functions needed? Suppose you have a number of objects of different
classes but you want to put them all in an array and perform a particular operation on
them using the same function call. For example, suppose a
graphics program includes several different shapes: a triangle, a ball, a square, and so on
. Each of these classes has a member function draw() that causes the object to be drawn
on the screen.
Now suppose you plan to make a picture by grouping a number of these elements
together, and you want to draw the picture in a convenient way. One approach is to create
an array that holds pointers to all the different objects in the picture. The array might be
defined like this: shape* ptrarr[100]; // array of 100 pointers to shapes If you insert
pointers to all the shapes into this array, you can then draw an entire picture using a
simple loop:

for(int j=0; j<N; j++)


ptrarr[j]->draw();

This is an amazing capability: Completely different functions are executed by the same
function call. If the pointer in ptrarr points to a ball, the function that draws a ball is
called; if it points to a triangle, the triangle-drawing function is called. This is called
polymorphism, which means different forms. The functions have the same appearance,
the draw() expression, but different actual functions are called, depending on the contents
of ptrarr[j]. Polymorphism is one of the key features of object-oriented programming,
after classes and inheritance. For the polymorphic approach to work, several conditions
must be met. First, all the different classes of shapes, such as balls and triangles, must be

Lab Manual: CS-103 (Object Orient Programming)


UNIVERSITY OF ENGINEERING AND TECHNOLOGY, TAXILA
DEPARTMENT OF COMPUTER SCIENCE
http://web.uettaxila.edu.pk

descended from a single base class (called shape in MULTSHAP). Second, the draw()
function must be declared to be virtual in the base class.

Limitations of Virtual Functions:

Slower: The function call takes slightly longer due to the virtual mechanism and makes it
more difficult for the compiler to optimize because it does not know exactly which
function is going to be called at compile time.
Difficult to Debug: In a complex system, virtual functions can make it a little more difficult to
figure out where a function is being called from.

b. Function overriding is a part of runtime polymorphism. Function overriding occurs when a


derived class has a definition for one of the member functions of the base class. That base function
is said to be overridden. In function overriding, more than one method has the same name with
different types of the parameter list. It is achieved by using virtual functions and pointers. It
provides slow execution as it is known at the run time. Thus, it is more flexible as all the things
executed at the run time.
#include <iostream>
using namespace std;
// Base class
class Vehicle {
public:
// Virtual function
virtual void sound() {
cout << "Vehicle makes a sound" << endl;
}
};

// Derived class

Lab Manual: CS-103 (Object Orient Programming)


UNIVERSITY OF ENGINEERING AND TECHNOLOGY, TAXILA
DEPARTMENT OF COMPUTER SCIENCE
http://web.uettaxila.edu.pk

class Car : public Vehicle {


public:
// Override sound() in Car class
void sound() override {
cout << "Car honks" << endl;
}
};

int main() {
// Create object of derived class
Car car;

// Call the overridden function


car.sound(); // Output: Car honks

return 0;
}
We define a base class Vehicle with a virtual function sound(), representing the sound made by a
vehicle. We define a derived class Car that inherits from Vehicle. In the Car class, we override the
sound() function with our own implementation that represents the sound of a car, "Car honks". In
the main() function, we create an object car of the Car class. We call the sound() function on the
car object. Since sound() is declared as virtual in the base class and overridden in the derived class,
the version of sound() specific to the Car class is invoked, resulting in "Car honks" being printed.

Lab Manual: CS-103 (Object Orient Programming)


UNIVERSITY OF ENGINEERING AND TECHNOLOGY, TAXILA
DEPARTMENT OF COMPUTER SCIENCE
http://web.uettaxila.edu.pk

Example : C++ program for function overriding

#include <bits/stdc++.h>
using namespace std;

class base
{ public:
virtual void print ()
{ cout<< "print base class" <<endl; }

void show ()
{ cout<< "show base class" <<endl; }
};

class derived:public base


{ public: void print () //print () is already virtual function in derived class, we could also declared
as virtual void print () explicitly
{ cout<< "print derived class" <<endl; }

void show ()
{ cout<< "show derived class" <<endl; }
};

//main function int


main()
{
base *bptr;
derived d; bptr =
&d;

//virtual function, binded at runtime (Runtime polymorphism)


bptr->print();

// Non-virtual function, binded at compile time bptr->show();

return 0;
}

Lab Manual: CS-103 (Object Orient Programming)


UNIVERSITY OF ENGINEERING AND TECHNOLOGY, TAXILA
DEPARTMENT OF COMPUTER SCIENCE
http://web.uettaxila.edu.pk

Output:

print derived class


show base class

The base class base defines two member functions: print() and show(), with print() declared as
virtual. The derived class derived inherits from base and overrides the print() function with its own
implementation. In the main() function, a pointer of type base is assigned the address of a derived
class object. When calling bptr->print(), the overridden print() function of the derived class is
invoked due to dynamic binding, displaying "print derived class". However, bptr->show() calls the
show() function of the base class, as it's not virtual, resulting in "show base class" being printed.
This demonstrates how function overriding and virtual functions enable runtime polymorphism,
allowing for flexible and dynamic behavior in object-oriented programming.

Lab Manual: CS-103 (Object Orient Programming)

You might also like