Sunteți pe pagina 1din 13

Riphah International University

Islamabad

LAB MANUAL

Lab Manual for Data structures & Algorithms

FACULTY OF COMPUTING (WISH)


Lab Manual Development Team

Supervision and Coordination


Tajwar Mehmood
Lecturer
Faculty of Computing

Lab Designers

Tehreem Shabbir
Teaching Fellow
Faculty of Computing
Table of Contents

Contents
Lab 4: Introduction to Operator Overloading & Templates................................................................. 5
1. Introduction .............................................................................................................................. 5
2. Activity Time boxing................................................................................................................... 5
3. Lab Manual Lecture [Expected time = 30 minutes] ........................................................ 5
4. Objective ................................................................................................................................... 5
5. Concept Map ............................................................................................................................. 5
5.1 The Structure of an Operator ............................................................................................. 5
5.2 Syntax ............................................................................................................................ 6
6. Templates.................................................................................................................................. 9
6.1 Function templates .................................................................................................................. 9
6.2 Class templates ...................................................................................................................... 10
7. Evaluation criteria.................................................................................................................... 13
8. Further Reading ....................................................................................................................... 13
8.1 Books ............................................................................................................................... 13
9.1 Out comes ............................................................................................................................. 13

––
Lab Manual for Programming Fundamentals
Lab 4: Introduction to Operator Overloading &
Templates
Lab 4: Introduction to Operator Overloading &
Templates
1. Introduction
In C++, we can make operators to work for user defined classes. This means C++ has the ability to provide
the operators with a special meaning for a data type, this ability is known as operator overloading.
For example, we can overload an operator ‘+’ in a class like String so that we can concatenate two strings
by just using +.
Other example classes where arithmetic operators may be overloaded are Complex Number, Fractional
Number, Big Integer, etc.

2. Activity Time boxing


Table 1: Activity Time Boxing
Task No. Activity Name Activity time Total Time
Lab Manual Lecture 30 min
Examples 20 min
Walkthrough Tasks 10 min
Practice Tasks 60 min
Tasks Evaluation 10-20 min

3. Lab Manual Lecture [Expected time = 30 minutes]

4. Objective
1. Learn Operator Overloading
2. Learn Templates

5. Concept Map
Operator Overloading • Operator overloading is the process of providing object specific functionality for
the base operators:
1. +
2. -
3. /
4. *
You can overload these to allow you to, for example, divide objects by each other or multiply them
together.

5.1 The Structure of an Operator


All operators, fundamentally, do two things:
1. Operate on one or more values (known as operands)
2. Return a value
Consider the example:
Int num = 4 + 5 ;

1. Operator is +
2. Operands and 4 and 5
3. Returns the sum of the two operands – 9

5.2 Syntax

An Unary operator is an operator that operates on a single operand and returns a new value.
Some of the unary operators are,
 ++ (Increment Operator)
 - - (Decrement operator)
 – (Unary Minus operator)
 ! (NOT Operator)

#include<iostream>

using namespace std;

//Steps for using Operator Overloading

/*

1. Create a class, with parameters.


2. Create a constructor, initialize with values
3. Create a Main class, Make objects.
4. Write overloaded function.
5. Call Overloaded Function.
*/

#include <iostream>

using namespace std;

class Test
{

private:

int count;

public:

Test(): count(5){}

void operator ++()

count = count+1;

void Display() { cout<<"Count: "<<count; }

};

int main()

Test t;

// this calls "function void operator ++()" function

++t;

t.Display();

return 0;

The binary operators take two arguments and following are the examples of Binary operators. You use
binary operators very frequently like addition (+) operator, subtraction (-) operator and division (/)
operator.

#include <iostream>

using namespace std;

class Box

{
public:

int length;

int breadth;

public:

Box()

length = 9;

breadth = 12;

Box operator +(Box &b)

Box box;

cout<<"box.breadth "<<box.breadth<<endl;

cout<<"This.breadth "<<this->breadth<<endl;

box.breadth = this->breadth + b.breadth;

return box;

};

int main()

Box Box1;

Box Box2;

Box Box3;

Box2.breadth = 11;

// Box1.breadth=5;

// this calls "function void operator +()" function


Box3 = Box1 + Box2;

int a = Box3.breadth;

cout<<"New Value is "<<a<<endl;

return 0;

6. Templates

6.1 Function templates


Function templates are special functions that can operate with generic types. This allows us to create a
function template whose functionality can be adapted to more than one type or class without repeating
the entire code for each type.

The format for declaring function templates with type parameters is:

template <class identifier> function_declaration;


template <typename identifier> function_declaration;

// function template

#include <iostream>

using namespace std;

template <typename T>

T GetMax (T a, T b)

T max;

if(a>b)

{ max = a; }

else

max=b;
return max;

int main () {

int i=5, j=6, k;

float l=10.7, m=5.77; float n;

k=GetMax(i,j);

n=GetMax(l,m);

cout <<"Int Type "<<k << endl;

cout << "Float Type "<< n << endl;

return 0;

6.2 Class templates


We also have the possibility to write class templates, so that a class can have members that use
template parameters as types. For example:

1 template <class T>


2 class number {
3 T values [2];
4 public:
5 number (T first, T second)
6 {
7 values[0]=first; values[1]=second;
8 }
9 };

The class that we have just defined serves to store two elements of any valid type. For example, if we
wanted to declare an object of this class to store two integer values of type int with the values 115 and
36 we would write:

number <int> myobject (115, 36);

this same class would also be used to create an object to store any other type:

number <double> myfloats (3.0, 2.18);


//Steps
/*
1. template <class T>
2. Create Class
3. wherever u need to give a data type, use T.
4. Define a function
5. In main() call function using templates like classname <datatype> object
(arguments)
*/

// class templates

#include <iostream>

using namespace std;

template <class T>

class mypair {

T a, b;

public:

mypair (T first, T second)

{a=first; b=second;}

T getmax ();

};

template <class T>

T mypair<T>::getmax ()

T retval;

retval = a>b? a : b;

return retval;

}
int main () {

mypair <int> myobject (100, 75);

cout << myobject.getmax();

return 0;

6. Practice Tasks
Task 1: [Time Required: 30 minutes]
Define a class IncrementDecrement
1. Declare a variable inside it .
2. Class must have at least one constructor i.e. Default constructor for initializing var to some default
value.
3. Write a function Display to show the value of var.
4. Write a function operator ++( ) inside which you have to increment the value of var, and return it as
well.
5. Inside main function, create an object of the class , say obj1.
6. Call Display() to show the initial value of i
7. Apply increment to obj1
8. Save the value of obj1 in some other object, say obj2
9. Call Display for Obj2 to display the increment
10. Also overload Decrement operator.

Task 2: [Time Required: 30 minutes]


Define a class Triangle with following members.
• double Base
• Double height
Provide Setters/Getters
Provide a function getArea to calculate area.
Inside main create two triangles
• Overload = = to compare two Triangles.
• Overload + operator to add two Triangles.
• Overload – operator to sub 2nd triangle from first one

Task 3: [Time Required: 10 minutes]


Write a program that instantiates three different array types int, float and char with a single constructor
a member function with use of typename T template. Then display the value of array for different data
types int, float and char. Start this question by first making the class.
Task 4: [Time Required: 10 minutes]
Swap numbers of type int, float and char using templates.
7. Evaluation criteria
The evaluation criteria for this lab will be based on the completion of the following tasks. Each task is
assigned the marks percentage which will be evaluated by the instructor in the lab whether the student
has finished the complete/partial task(s).

Table 3: Evaluation of the Lab


Sr. No. Task No Description Marks
1 Quiz 1
2 1 Task 1 1
3 2 Task 2 1
4 3 Task 3 1
5 4 Task 4 1

8. Further Reading
8.1 Books
9. The slides and reading material can be accessed from the folder of the class instructor available at
vle.

9.1 Out comes


The outcomes of this lab were:
a) Learnt Operator Overloading
b) Learnt Templates
_____________________________________________________________________________________

S-ar putea să vă placă și