Docsity

Understanding Friend Functions and Templates in Object-Oriented Programming, Slides of Object Oriented Programming

Partial preview of the text

Download Understanding Friend Functions and Templates in Object-Oriented Programming and more Slides Object Oriented Programming in PDF only on Docsity!

ObjectObject--Oriented ProgrammingOriented Programming (OOP)(OOP)

Lecture No. 38 Lecture No. 38

Templates and FriendsTemplates and Friends – – Rule 1Rule 1

► ► When an ordinary function or class isdeclared as friend of a class template then itWhen an ordinary function or class is declared as friend of a class template then it

becomes friend of each instantiation of thattemplate becomes friend of each instantiation of that template

Templates and FriendsTemplates and Friends – – Rule 2Rule 2

► ► When a friend function / class template isinstantiated with the type parameters ofWhen a friend function / class template is instantiated with the type parameters of

class template granting friendship then itsinstantiation for a specific type is a friend of class template granting friendship then its instantiation for a specific type is a friend of

that class template instantiation for thatparticular type that class template instantiation for that particular type

template< class U >void template< class U > void doSomethingdoSomething( U u ) {( U u ) { B< U > ib;ib.data = 78; B< U > ib; ib.data = 78; } }

► ► BecauseB< int >Because B< int > doSomething()doSomething() always instantiatesalways instantiates

class B< int > { class B< int > {int data; int data; friend void doSomething( int );friend A< int >; friend void doSomething( int ); friend A< int >; }; }; docsity.com

Templates and FriendsTemplates and Friends – – Rule 3Rule 3

► ► When a friend function / class templatetakes different type parameters from theWhen a friend function / class template takes different type parameters from the

class template granting friendship then itseach instantiation is a friend of each class template granting friendship then its each instantiation is a friend of each

instantiation of the class template grantingfriendship instantiation of the class template granting friendship

template< class T >class A { template< class T > class A { void method() { void method() {B< char > cb; B< char > cb; // OK!// OK! cb.data = 8;B< int > ib; cb.data = 8; B< int > ib; } } ib.data = 9;^ ib.data = 9; }; }; docsity.com

template< class T >class B { template< class T > class B { T data;template< class U > T data; template< class U > }; }; friend class A;^ friend class A;

template< class U >void doSomething( U u ) { template< class U > void doSomething( U u ) { B< int > ib;ib.data = 56; B< int > ib; ib.data = 56; // OK// OK } }