Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 14: Overloading and Templates

Similar presentations


Presentation on theme: "Chapter 14: Overloading and Templates"— Presentation transcript:

1 Chapter 14: Overloading and Templates
C++ Programming: Program Design Including Data Structures, Second Edition Chapter 14: Overloading and Templates

2 Objectives In this chapter you will: Learn about overloading
Become aware of the restrictions on operator overloading Examine the pointer this Learn about friend functions C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

3 Objectives Explore the members and nonmembers of a class
Discover how to overload various operators Learn about templates Explore how to construct function templates and class templates C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

4 Operator Overloading The only built-in operations on classes are
assignment and member selection Other operators cannot be applied directly to class objects C++ allows you to extend the definitions of most of the operators to work with classes This is called operator overloading C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

5 Operator Overloading (continued)
Most existing operators can be overloaded to manipulate class objects Can overload most C++ operators Cannot create new operators Write an operator function to overload an operator C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

6 Operator Overloading (continued)
The name of the function that overloads an operator is the reserved word operator followed by the operator to be overloaded For example, to overload >=, write a function called: operator>=(…) C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

7 Overloading the operator
C++ allows us to redefine the meaning of the relational operators in terms of the data members of a class this redefining of an operator symbol is called overloading the operator C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

8 Overloading Binary Operators arithmetic and relational
Binary operators can be member functions Function Prototype: returnType operator# (const className&) const; where # is the binary operator to overload, returnType is the type of value returned className is the name of the class for which the operator is being overloaded Function Definition: returnType className::operator# (const className& otherObject) { //algorithm to perform the operation return value; } C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

9 // SPECIFICATION FILE ( strtype.h ) const int MAX_CHARS = 200 ;
enum InType { ALPHA_NUM, ALPHA, NON_WHITE, NOT_NEW } ; class StrType { public : StrType ( ) ; // DEFAULT CONSTRUCTOR void MakeEmpty ( ) ; void GetString ( bool skip, InType inString, std::ifstream& inFile ) ; void PrintToScreen ( bool newLine ) const ; void PrintToFile ( bool newLine , std::ofstream& outFile ) const ; . . // OVERLOADED OPERATORS – make comparison simpler and // more robust //syntax: the word operator followed by the symbol to be overloaded bool operator< (const StrType& otherString ) const ; bool operator== (const StrType& otherString ) const ; private : char letters [MAX_CHARS + 1 ] ; } ; expanded by J. Goetz, 2004

10 StrType Class Interface Diagram
MakeEmpty Private data: letters GetString ‘c’ ’a’ ’t’ ’\0’ ... PrintToScreen . operator< operator== expanded by J. Goetz, 2004

11 class StrType Default Constructor
// IMPLEMENTATION FILE (strtype.cpp) #include “strtype.h” // also appears in client code #include <cstring> StrType :: StrType( ) // DEFAULT CONSTRUCTOR // Pre: None. // Post: letters is empty string. { letters[0] = ‘\0’ ; } expanded by J. Goetz, 2004

12 // IMPLEMENTATION FILE continued (strtype.cpp)
// operator< OVERLOADED bool StrType :: operator< ( const StrType& otherString ) const // Pre: self is initialized. otherString is initialized. // Post: Returns true if self precedes otherString // lexicographically. Otherwise, returns false. { int result ; result = std::strcmp ( letters, otherString.letters ) ; // p.1475 if ( result < 0 ) return true; else return false ; } expanded by J. Goetz, 2004

13 // IMPLEMENTATION FILE continued (strtype.cpp)
// operator== OVERLOADED bool StrType :: operator==(const StrType& otherString ) const // Pre: self is initialized. otherString is initialized. // Post: Returns true if self is identical to otherString // lexicographically. Otherwise, returns false. { int result ; result = std::strcmp ( letters, otherString.letters ) ; if ( result == 0 ) return true; else return false ; } expanded by J. Goetz, 2004

14 operator functions as member functions
Note: All overloaded binary operators are member functions of StrType When the client code includes: StrType yourString; StrType myString; if (myString < yourString) the compiler translates into the function call: myString.operator< (yourString) or if (myString == yourString) The respective member functions from StrType are invoked. C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

15 Syntax for Operator Functions
The syntax of an operator function heading: returnType operator operatorSymbol (arguments) e.g bool operator== (const StrType& otherString ); The operator function is value-returning operator is a reserved word To overload an operator for a class: Include operator function in the class definition Write the definition of the operator function C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

16 Some Restrictions When overloading an operator:
Cannot change precedence or associativity Default arguments cannot be used Cannot change the number of arguments that an operator takes Cannot create new operators These operators cannot be overloaded . .* :: ?: sizeof Meaning of how an operator works with built-in types, such as int, remains the same 7. Operators can be overloaded either for user-defined objects or for a combination of user-defined and built-in objects C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

17 Pointer this Every object of a class maintains a (hidden) pointer to itself called this this is a reserved word When an object invokes a member function the this pointer is referenced by the member function C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

18 Pointer this test test :: one() // return the value of the entire object { … return *this; } Let have: test x, y; y = x.one(); // copies the value of object x into object y. // The data members of x are copied into the corresponding data members of y // object x invokes function one, the pointer this in one() refers to object x, // so this is an address of x // * this means the value of x C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

19 // thisPointerIllus.cpp #include <iostream>
class thisPointerClass // thisPointerIllus.h { public: void set(int a, int b, int c); void print() const; thisPointerClass updateXYZ(); // Postcondition: x = 2 * x; y = y + 2; // z = z * z; thisPointerClass(int a = 0, int b = 0, int c = 0); private: int x; int y; int z; }; // thisPointerIllus.cpp #include <iostream> #include "thisPointerIllus.h" using namespace std; void thisPointerClass::set(int a, int b, int c) { x = a; y = b; z = z; } void thisPointerClass::print() const cout << "x = " << x << ", y = " << y << ", z = " << z << endl; thisPointerClass thisPointerClass::updateXYZ() x = 2 * x; y = y + 2; z = z * z; return *this; thisPointerClass::thisPointerClass(int a, int b, int c) z = c; //Chapter 14: this pointer illustration p.765 //Ch14_thisPointerIlusTestProg.cpp #include <iostream> #include "thisPointerIllus.h" using namespace std; int main() { thisPointerClass object1(3, 5, 7); //Line 1 thisPointerClass object2; //Line 2 cout << "Object 1: "; //Line 3 object1.print(); // //Line 4 object2 = object1.updateXYZ(); // //Line 5 cout << "After updating object1: "; //Line 6 object1.print(); // //Line 7 cout << "Object 2: "; //Line 8 object2.print(); // //Line 9 return 0; } C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

20 #include <iostream> #include <string>
//personType.h #include <string> using namespace std; class personType { public: void print() const; //Function to output the first name and last name //the form firstName lastName void setName(string first, string last); //Function to set firstName and lastName according //to the parameters. //Postcondition: firstName = first; lastName = last personType& setFirstName(string first); //Function to set the first name. //Postcondition: firstName = first // After setting the first name, a reference // to the object, that is, the address of the // object, is returned. personType& setLastName(string last); //Function to set the last name. //Postcondition: lastName = last // After setting the last name, a reference string getFirstName() const; //Function to return the first name. //Postcondition: The value of the data member firstName // is returned. string getLastName() const; //Function to return the last name. //Postcondition: The value of the data member lastName personType(string first = "", string last = ""); //constructor //Sets firstName and lastName according to the parameters private: string firstName; //variable to store the first name string lastName; //variable to store the last name }; //personTypeImp.cpp #include <iostream> #include <string> #include "personType.h" using namespace std; void personType::print() const { cout << firstName << " " << lastName; } void personType::setName(string first, string last) firstName = first; lastName = last; string personType::getFirstName() const return firstName; string personType::getLastName() const return lastName; //constructor with parameters personType::personType(string first, string last) personType& personType::setLastName(string last) return *this; personType& personType::setFirstName(string first) C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

21 //personTypeImp.cpp #include <iostream> #include <string> #include "personType.h" using namespace std; void personType::print() const { cout << firstName << " " << lastName; } void personType::setName(string first, string last) firstName = first; lastName = last; string personType::getFirstName() const return firstName; string personType::getLastName() const return lastName; //constructor with parameters personType::personType(string first, string last) personType& personType::setLastName(string last) return *this; personType& personType::setFirstName(string first) //Test Program: this pointer // testProg.cpp #include <iostream> #include <string> #include "personType.h" using namespace std; int main() { personType student1("Angela", "Clodfelter"); //Line 1 personType student2; //Line 2 personType student3; //Line 3 cout << "Line 4 -- Student 1: "; //Line 4 student1.print(); //Angela Clodfelter //Line 5 cout << endl; //Line 6 student2.setFirstName("Shelly").setLastName("Malik"); //Line 7 // the associativity of the dot operator is from left to right cout << "Line 8 -- Student 2: "; //Line 8 student2.print(); //Shelly Malik //Line 9 cout << endl; //Line 10 student3.setFirstName("Chelsea"); //Line 11 cout << "Line Student 3: "; //Line 12 student3.print(); //Chelsea //Line 13 cout << endl; //Line 14 student3.setLastName("Tomek"); //Line 15 cout << "Line Student 3: "; //Line 16 student3.print(); //Chelsea Tomek //Line 17 cout << endl; //Line 18 return 0; } C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

22 Friend Functions of Classes
friend function: a function defined outside the scope of a class A friend is a nonmember function However, has access to private data members To make a function friend to a class The reserved word friend precedes the function prototype in the class definition C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

23 Friend Functions of Classes
class classIllusFriend { friend void two(…); } // two(…) is declared as a friend of class classIllusFriend When writing the friend definition The name of the class and the scope resolution operator are not used The word friend appears only in the function prototype (in the class definition), not in the definition of the friend function!!! C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

24 Operator Functions - rules
To make an operator function be a member or nonmember function of a class: A function that overloads any of the operators (), [], ->, or = must be a member of the class Suppose an operator op is overloaded for a class, say nameClass If leftmost operand of op is an object of a different type, the function that overloads the operator op for nameClass must be a nonmember (friend) of the class nameClass If the operator function that overloads the operator op for nameClass is a member of nameClass, then when applying op on objects of nameClass, leftmost operand of op must be type nameClass Most of the operators can be overloaded either as member or nonmember functions C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

25 operator functions as member functions
Note: All overloaded binary operators are member functions of StrType When the client code includes: StrType yourString; StrType myString; if (myString < yourString) the compiler translates into the function call: myString.operator< (yourString) or if (myString == yourString) The respective member functions from StrType are invoked. C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

26 operator functions as nonmember functions
Note: All overloaded binary operators are member functions of StrType When the client code includes: StrType yourString; StrType myString; if (myString < yourString) the compiler translates into the function call: operator< (myString, yourString) the function operator< is neither a member of the object myString nor a member of the object yourString C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

27 operator function as a nonmember function
Prototype: friend returnType operator# (const className&, const className&); where # stands for the binary operator to be overloaded Definition: returnType operator# (const className& firstObject, const className& secondObject) { // alg. to perform the operation return value; } where returnType is the type of the value returned by the function className is the name of the class for which the operator is being overloaded C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

28 // SPECIFICATION FILE ( strtype.h ) const int MAX_CHARS = 200 ;
enum InType { ALPHA_NUM, ALPHA, NON_WHITE, NOT_NEW } ; class StrType { // the friend function typically is placed before any member function declaration // OVERLOADED OPERATORS – make comparison simpler and // more robust //syntax: the word operator followed by the symbol to be overloaded friend bool operator< (const StrType&, const StrType& ) const ; friend bool operator== (const StrType&, const StrType& ) const ; public : StrType ( ) ; // DEFAULT CONSTRUCTOR void MakeEmpty ( ) ; void GetString ( bool skip, InType inString, std::ifstream& inFile ) ; void PrintToScreen ( bool newLine ) const ; void PrintToFile ( bool newLine , std::ofstream& outFile ) const ; private : char letters [MAX_CHARS + 1 ] ; } ; C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

29 operator function as a nonmember function
// operator< OVERLOADED is used as a nonmember function of the class StrType bool operator< (const StrType& myString, const StrType& otherString) const // Pre: self is initialized. otherString is initialized. // Post: Returns true if myString precedes otherString // lexicographically. Otherwise, returns false. { int result ; result = std::strcmp (myString.letters, otherString.letters ) ; // p.1475 if ( result < 0 ) return true; else return false ; } expanded by J. Goetz, 2004

30 class operator function as a nonmember function
example: Rectangle p.779 14/Source Code/Ch14_Example14-5_binaryOprAsFriend/ or on the instructors disk: ..\Source_Code\Chapter 14\Source Code\Ch14_Example14-5_binaryOprAsFriend\rectangleType.h ..\Source_Code\Chapter 14\Source Code\Ch14_Example14-5_binaryOprAsFriend\rectangleTypeImp.cpp ..\Source_Code\Chapter 14\Source Code\Ch14_Example14-5_binaryOprAsFriend\testOpOverLoadClass.cpp C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

31 Overloading << and >> Operators
Suppose an operator >> or << is overloaded for a class, say nameClass If leftmost operand of >> or << is an object of a different type, the function that overloads the operator >> or << for nameClass must be a nonmember (friend) of the class nameClass So the operator function that overloads the insertion operator << or the extraction operator >> for a class must be a nonmember of that class Consider the following expression: cin>>x In this expression, the leftmost operand of >> (cin, x). cin is an istream variable, not an object of the type className The almost the same consideration we can have for cout << x C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

32 Overloading the Stream Insertion Operator
Function Prototype: friend ostream& operator<< (ostream&, const className&); Function Definition: ostream& operator<< (ostream& osObject, const className& cObject) { //local declaration, if any //Output the members of cObject. //osObject << . . . //Return the stream object. return osObject; } C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

33 Overloading the Stream Insertion Operator
ostream& operator<< (ostream& osObject, const className& cObject) { //local declaration, if any //Output the members of cObject. //osObject << . . . //Return the stream object. return osObject; } Both parameters are reference parameters The first parameter (osObject) is a reference to an ostream object The second parameter is usually a const reference to a particular class The function return type is a reference to an ostream object Example: ostream& operator << (ostream& osObject, const rectangleType& rectangle) { osObject << "Length = " << rectangle.length << "; Width = " << rectangle.width; return osObject; } C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

34 the compiler translates ( is equivalent to)
ostream& operator<< (ostream& osObject, const className& cObject) { } cout << myRectangle; the compiler translates ( is equivalent to) operator<< (cout, myRectangle); // both are objects, returns a reference to object cout << myRectangle << yourRectangle; the compiler translates operator<< (operator<< (cout, myRectangle), yourRectangle); C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

35 Overloading the Stream Extraction Operator
Function Prototype: friend istream& operator>> (istream&, const className&); Function Definition: istream& operator>> (istream& isObject, const className& cObject) { //local declaration, if any //Read the data into cObject. //isObject << . . . //Return the stream object. return isObject; } C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

36 Overloading the Stream Extraction Operator
istream& operator>> (istream& isObject, const className& cObject) { //local declaration, if any //Read the data into cObject. //isObject << . . . //Return the stream object. return isObject; } Both parameters are reference parameters The first parameter (isObject) is a reference to an istream object The second parameter is usually a const reference to a particular class The function return type is a reference to an istream object see example: de/Chapter%2014/Source%20Code/Ch14_Example14- 6_streamOpr/ Example: istream& operator >> (istream& isObject, rectangleType& rectangle) { isObject >> rectangle.length >> rectangle.width; return isObject; } C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

37 Overloading the Assignment Operator
Function Prototype: const className& operator= (const className&); Only one formal parameter Formal parameter is usually a const reference to a particular class Function return type is a const reference to a particular class C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

38 Overloading the Assignment Operator
Function Definition: const className& className::operator= (const className& rightObject) { // local declaration, if any if (this != &rightObject) //avoid self-assignment // b/c they would waste // computer time // algorithm to copy rightObject // into this object } // Return the object assigned. return *this; example: const cAssignmentOprOverload& cAssignmentOprOverload::operator= (const cAssignmentOprOverload& otherList) { if (this != &otherList) //avoid self-assignment; Line 1 delete [] list; //Line 2 maxSize = otherList.maxSize; //Line 3 length = otherList.length; //Line 4 list = new int[maxSize]; //Line 5 assert(list != NULL); //Line 6 incl: cassert for (int i = 0; i < length; i++) //Line 7 list[i] = otherList.list[i]; //Line 8 } return *this; //Line 9 e.g. intList3 = intList2 = intList1; // equivalent to intList3.operator=(intList2.operator=(intList1)); C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

39 Overloading Unary Operators
To overload a unary operator for a class: If the operator function is a member of the class, it has no parameters If the operator function is a nonmember (friend), it has one parameter C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

40 Overloading ++ and -- The increment operator has two forms
Pre-increment (++u) Post-increment (u++) u is a variable, say of the type int Pre-increment: the value of u is incremented by 1 before using u in an expression Post-increment: the value of u is used in the expression before it is incremented by 1 C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

41 Overloading the Pre-Increment Operator as a Member vs Nonmember Function
Function Prototype: className operator++(); Function Definition: className className::operator++() { //increment the value of the object by 1 return *this; } Function Prototype: friend className operator++(className&); Function Definition: className operator++(className& incObj) { //increment incObj by 1 return incObj; } example: rectangleType rectangleType :: operator++ () { ++length: ++width; return *this; // return the incremented value // of the object } // client code use: ++myRectangle; example: rectangleType operator++ (rectangleType& rectangle) { (rectangleType.length)++; (rectangleType.width)++; return rectangle; // return the incremented value // of the object } // client code use: ++yoursRectangle; C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

42 Overloading the Post-Increment Operator as a Member vs Nonmember Function
Function Prototype: friend className operator++(className&, int); Function Definition: className operator++(className& incObj, int u) {// use a dummy parameter int to distinguish between pre- and post- increment operator overloading className temp = incObj; //copy incObj into temp //increment incObj return temp; //return the old value of the object } Function Prototype: className operator++(int); Function Definition: className className::operator++(int u) { // use a dummy parameter int to distinguish between pre- and post- increment operator overloading className temp = *this; //use this pointer to copy //the value of the object //increment the object return temp; //return the old value of the object } example: rectangleType rectangleType :: operator++ (rectangleType& rectangle, int u) { rectangleType temp = rectangle; // copy into temp (rectangleType.length)++; (rectangleType.width)++; return temp; // return the old value of the object } example: rectangleType rectangleType :: operator++ (int u) { rectangleType temp = *this; // use this pointer to copy the value // of the object length++: width++; return temp; // return the old value of the object } C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

43 Post-Increment operator
// client code: myRectangle++; is compiled to myRectangle.operator++(0); C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

44 Operator Overloading: Member Versus Nonmember
Certain operators must be overloaded as member functions and some must be overloaded as nonmember (friend) functions The binary arithmetic operator + can be overloaded either way Overload + as a member function Operator + has direct access to data members of one of the objects Need to pass only one object as a parameter C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

45 Operator Overloading: Member Versus Nonmember (continued)
Overload + as a nonmember function Must pass both objects as parameters Could require additional memory and time to make a local copy of the data Conclusion: For efficiency purposes, overload operators as member functions Complex Number example: C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

46 Classes and Pointer Data Members
Classes with pointer data members must: Explicitly overload the assignment operator To avoid shallow copying of data for classes with a pointer data member, overload the assignment operator Include the copy constructor To avoid shallow initializaton of data for classes with a pointer data member, include the copy constructor Include the destructor A class destructor is used to deallocate the dynamic memory pointed to by the data member. myStringClass: C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

47 Overloading the Subscript Operator
Type is the data type of the array elements //Overload the operator [] for constant arrays const Type& className::operator[ ](int index) const { assert(0 <= index && index < arraySize); // include in the file: cassert p.1469 return list[index]; //return a pointer of the //array component } //Overload the operator [] for nonconstant arrays Type& className::operator[ ](int index) const C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

48 Recollection of Function Overloading
Overloading a function: refer to have several functions with the same name, but different parameters Parameter types determine which function will execute Must provide the definition of each function C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

49 Templates – overloading a code
Templates: a single code body for a set of related functions (called function template) and related classes (called class template) The syntax for templates is: template <class Type> //Type of the data declaration; // a function declaration or a class declaration C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

50 Templates (continued)
template is a reserved word The word class in the heading refers to any user-defined type or built-in type Type is called a formal parameter to the template Just as variables are parameters to functions Data types are parameters to templates C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

51 Function Templates The syntax of the function template is: Type
template<class Type> function definition; where Type is called a formal parameter of the template Type Specifies type of parameters to the function Specifies return type of the function Declares variables within the function C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

52 Class Templates template<class Type>
Class templates: a single code segment represents a set of related classes Syntax: template<class Type> class declaration Called parameterized types A specific class is made based on the parameter type C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

53 Class Templates (continued)
A template instantiation can be created with either a built-in or user-defined type The function members of a class template are considered function templates C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

54 What is a Class Template?
A C++ language construct that allows the compiler to generate multiple versions of a class type or a function by allowing parameterized types. The formal parameter appears in the class template definition, and the actual parameter appears in the client code. Both are enclosed in pointed brackets, < >. The template allows the client program to specify the type of the items on the structure at the time an object of the data type is defined!!!. expanded by J. Goetz, 2004

55 StackType<int> numStack;
ACTUAL PARAMETER StackType<int> numStack; top [MAX_ITEMS-1] . [ 3 ] [ 2 ] [ 1 ] items [ 0 ] 55 expanded by J. Goetz, 2004

56 StackType<float> myStack;
ACTUAL PARAMETER StackType<float> myStack; top [MAX_ITEMS-1] . [ 3 ] [ 2 ] [ 1 ] items [ 0 ] 56 expanded by J. Goetz, 2004

57 StackType<StrType> nameStack;
ACTUAL PARAMETER StackType<StrType> nameStack; top [MAX_ITEMS-1] . [ 3 ] Bradley [ 2 ] Asad [ 1 ] Rodrigo items [ 0 ] Max 57 expanded by J. Goetz, 2004

58 //--------------------------------------------------------
// CLASS TEMPLATE DEFINITION (specification and definitions) // goes into StackType.h // and use #include “StackType.h” in the *.cpp client code #include "ItemType.h" // for MAX_ITEMS and ItemTyp template<class ItemType> // ItemType = formal parameter class StackType { public: StackType( ); void MakeEmpty( ); bool IsEmpty( ) const; bool IsFull( ) const; void Push( ItemType item ); void Pop(); ItemType StackType::Top(); private: int top; ItemType items[MAX_ITEMS]; }; 58 expanded by J. Goetz, 2004

59 template<class ItemType> // formal parameter
// SAMPLE CLASS MEMBER FUNCTIONS = FUNCTION TEMPLATES - goes into // StackType.h // template<class ItemType> // formal parameter StackType<ItemType>::StackType( ) { top = -1; } template<class ItemType> // formal parameter StackType<ItemType>::MakeEmpty( ) template<class ItemType> // formal parameter void StackType<ItemType>::Push ( ItemType newItem ) if (IsFull()) throw FullStack(); top++; items[top] = newItem; // STATIC ARRAY IMPLEMENTATION 59 expanded by J. Goetz, 2004

60 Client code *.cpp StackType<int> myStack;//template argument is a data type name StackType<float> yourStack; StackType<StrType> anotherStack; myStack.Push(45); yourStack.Push(45.35); At compile time, the compiler generates (instantiates) 3 distinct class types called template classes and gives its own internal name to each of the types (something like this): StackType_int myStack; StackType_float yourStack; StackType_StrType anotherStack; Generated template classes are opposed to the class template from which they are created. C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

61 Substitution When the compiler instantiates a template,
it literally substitutes the arguments for the parameter throughout the class template/function template. Passing an argument to a template has an effect at compile time. For example , when the compiler encounters StackType<float> in the client code, it generates a new class/function definition by substituting float for every occurrence of ItemType in the class template/function definition. class StackType_float { public: StackType( ); void MakeEmpty( ); bool IsEmpty( ) const; bool IsFull( ) const; void Push( float item ); //* void Pop(); //* float Top(); const; private: int top; float items[MAX_ITEMS]; //* }; C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

62 Using class templates The actual parameter to the template is a DATA TYPE name, (not a variable when we pass arguments to functions at run time). Any type can be used, either built-in or user-defined. When using class templates, both the specification and implementation (function definitions) should be located in the same file StackType.h, instead of in separate .h and .cpp files. The compiler cannot instantiate a function template unless it knows actual parameter to the template which appears in the client code. So the compiler has to have all the source code – both the member functions and the client code – available to it at once. 62 expanded by J. Goetz, 2004

63 Class Template A useful perspective on templates is this:
An ordinary class definition is a pattern for stamping out individual variables or objects A class template is a pattern for stamping out individual data types. C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

64 Header File of a Class Template
Passing a data type parameter to a class template and function template take effect at compile time Passing parameters to a function takes effect at run time C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

65 Header File of a Class Template
Cannot compile the implementation file independently of the client code Can put class definition and the definitions of the function templates directly in the client code Can put class definition and the definitions of the function templates in the same header file We will put the class definition and the function definitions in the same header file Another alternative: put class definition and function definitions in separate files However, include directive to implementation file at the end of header file C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

66 Header File of a Class Template
In either case, function definitions and client code are compiled together C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

67 Summary An operator that has different meanings with different data types is said to be overloaded Any function that overloads an operator is called an operator function operator is a reserved word Operator functions are value-returning Operator overloading provides the same concise notation for user-defined data types as for built-in data types C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

68 Summary Only existing operators can be overloaded
The pointer this refers to the object A friend function is a nonmember of a class If an operator function is a member of a class The leftmost operand of the operator must be a class object (or a reference to a class object) of that operator’s class C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004

69 Summary Every instance of an overloaded function has different sets of parameters Templates: Function template: a single code segment for a set of related functions Class template: a single code segment for a set of related classes Class templates are called parameterized types C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004


Download ppt "Chapter 14: Overloading and Templates"

Similar presentations


Ads by Google