Lab-12 Edc

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

Department of Computing

CS 212: Object Oriented Programming

Class: BEEE - 13B


Fall 2022

Lab12: Templates
Lab 12: Templates

[Azad’s Law: The one facilitating cheating will be punished with 0 marks]

The objective of this lab is to re-inforce the concept of templates within C++.

Task # 1: Function Templates

In this task you need to write a template function to find an element within an array of
arbitrary data type.

T* find (T* array, int size, T& x)

Test this function using an array of

● Integers
● Doubles
● Complex Numbers.

There should be the following three files.


1. templateFunc.h - contains function declaration for the find template
2. templateFunc.cpp - contains function implementation for the find template
3. CComplex.h - contains declaration for your complex class
4. CComplex.cpp - contains implementation for your complex class
5. Main.cpp - Instantiating different types of find functions

int main() {

int intNumbers[3] = {10,100,1000} ;


int* pIntNumber = find(intNumbers, 3, 100);
cout << *pIntNumber;
CComplex cNumbers[3];
cNumers[0].SetReal(0.0);
cNumers[0].SetImag(1.0);

cNumers[1].SetReal(2.0);
cNumers[1].SetImag(2.0);

cNumers[2].SetReal(10.0);
cNumers[2].SetImag(1.0);

CComplex xNumber(2.0,2.0);
CComplex* pCNumber = find(cNumbers, 3, xNumber);
cout << *pCNumber;

return 0;
}
Task # 2: Class Templates

In this task you need to build a Vector template class to hold elements of different data
types. Your vector class should support the following functionality (see lecture notes).

● Constructor
● Destructor
● push_back - Add elements at the end of a vector
● pop_back - Remove elements from the end of a vector
● at(index) - Access a particular element of a vector
● Assignment Operator - Assign a particular element of a vector
● Print - Print all the elements of the vector
● GetSize - Return size of the vector

There should be the following 5 files.


1. Vector.h - contains Vector class declaration
2. Vector.cpp - contains Vector class implementation
3. Main.cpp - Instantiating multiple vectors

Vector<int> numbers;

numbers. pus_back(2);
numbers. pus_back(3);
numbers.print(); // 2, 3

numbers. pus_back(5);
numbers.print(); // 2, 3 , 5

numbers. pop_back();
numbers.print(); // 2, 3

numbers.at(0) = 10;
numbers.at(1) = 30;
numbers.print(); // 10, 30
Vector<CComplex> cNumbers;

cNumbers. pus_back(CComplex(2,2));
cNumbers. pus_back(CComplex(3,3));

cNumbers.print(); // (2,2), (3,3)

CComplex newNumber(100,100);
cNumbers. pus_back(newNumber);
cNumbers.print(); // (2,2), (3,3), (100,100)

cNumbers. pop_back();
cNumbers.print(); // (2,2), (3,3)

cNumbers.at(0) = CComplex(-1,-2);
cNumbers.print(); // (-1,-2), (3,3)

You might also like