Docsity

Object-Oriented Programming: Printing Arrays and Function Templates, Slides of Object Oriented Programming

Partial preview of the text

Download Object-Oriented Programming: Printing Arrays and Function Templates and more Slides Object Oriented Programming in PDF only on Docsity!

Object

Object

Oriented Programming

Oriented Programming

(OOP)

(OOP)

Lecture No. 32

Lecture No. 32

...Motivation

...Motivation

► ► What if we want to print an array ofWhat if we want to print an array of

characters? characters?

void printArray(char* array,

void printArray(char* array,

int size) int size)

for ( int i = 0; i < size; i++ ) for ( int i = 0; i < size; i++ )

cout << array[ i ] <<

cout << array[ i ] << “

...Motivation

...Motivation

► ► What if we want to use anWhat if we want to use an ArrayArray class thatclass that

wraps arrays of double? wraps arrays of double?

class Array { class Array {

double* pArray;

double* pArray;

int size; int size;

public:

public:

...Motivation

...Motivation

►

►

Now if we want to add a function sum to

Now if we want to add a function sum to

Array Array class, we have to change all the threeclass, we have to change all the three

classes

classes

Function Templates

Function Templates

►

►

A function template can be parameterized

A function template can be parameterized

to operate on different types of data

to operate on different types of data

Example

Example

Function Templates

Function Templates

► ► Following function template prints an arrayFollowing function template prints an array

having almost any type of elements: having almost any type of elements:

template< typename T >

template< typename T >

void printArray( T* array, int size ) void printArray( T* array, int size )

for ( int i = 0; i < size; i++ ) for ( int i = 0; i < size; i++ )

cout << array[ i ] <<

cout << array[ i ] << “

Explicit Type Parameterization

Explicit Type Parameterization

int main() { int main() {

int x; int x;

x = getInput< int >();

x = getInput< int >();

double y;

double y;

y = getInput< double >(); y = getInput< double >();

Example

Example

User Specializations

User Specializations

template< typename T > template< typename T >

bool isEqual( T x, T y ) { bool isEqual( T x, T y ) {

return ( x == y );

return ( x == y );