Docsity

Object-Oriented Programming: Templates, Static Members, and Generic Algorithms, Slides of Object Oriented Programming

Partial preview of the text

Download Object-Oriented Programming: Templates, Static Members, and Generic Algorithms and more Slides Object Oriented Programming in PDF only on Docsity!

Object

Object

Oriented Programming

Oriented Programming

(OOP)

(OOP)

Lecture No. 39

Lecture No. 39

Templates & Static Members

Templates & Static Members

template< class T > template< class T >

class A { class A {

public:

public:

static int data;

static int data;

static void doSomething( T & );

static void doSomething( T & );

Templates

Templates

Conclusion

Conclusion

►

►

Templates affect reliability of a program

Templates affect reliability of a program

template< typename T >

template< typename T >

bool isEqual( T x, T y ) {

bool isEqual( T x, T y ) {

return ( x == y ); return ( x == y );

Generic Algorithms Revisited

Generic Algorithms Revisited

template< typename P, typename T > template< typename P, typename T >

P find( P start, P beyond, P find( P start, P beyond,

const T& x ) {

const T& x ) {

while ( start != beyond &&

while ( start != beyond &&

*start != x )

*start != x )

++start; ++start;

return start; return start;

Example

Example

Vector

Vector

template< class T >

template< class T >

class Vector { class Vector {

private:

private:

T* ptr; T* ptr;

int size;

int size;

int index; int index; // initialized with zero// initialized with zero

public:

public:

Vector( int = 10 );

Vector( int = 10 );

Example

Example

Vector

Vector

template< class T >

template< class T >

int Vector< T >::getIndex() const { int Vector< T >::getIndex() const {

return index;

return index;

template< class T >

template< class T >

void Vector< T >::setIndex( int i ) { void Vector< T >::setIndex( int i ) {

if ( index >= 0 && index < size )

if ( index >= 0 && index < size )

index = i; index = i;

Example

Example

Vector

Vector

int main() {

int main() {

Vector iv( 3 ); Vector iv( 3 );

iv[0] = 10;

iv[0] = 10;

iv[1] = 20; iv[1] = 20;

iv[2] = 30;

iv[2] = 30;

Vector beyond( iv ),found( 3 ); Vector beyond( iv ),found( 3 );

beyond.setIndex( iv.getSize() );

beyond.setIndex( iv.getSize() );

found = find( iv, beyond, 20 ); found = find( iv, beyond, 20 );

cout<<

cout<< “

Index:

Index: ”

<<found.getIndex();

<<found.getIndex();

return 0; return 0;

Problems

Problems

►

►

Our generic algorithm now works fine with

Our generic algorithm now works fine with

container container VectorVector

►

►

However there are some problems with the

However there are some problems with the

iteration approach provided by class iteration approach provided by class VectorVector