! Search: find a given target item in an array, ! Linear Search: Very simple search method: ! Operators such as =, +, <, and others can be

Similar documents
Operator Overloading and Templates. Linear Search. Linear Search in C++ second attempt. Linear Search in C++ first attempt

l Operators such as =, +, <, can be defined to l The function names are operator followed by the l Otherwise they are like normal member functions:

! Operators such as =, +, <, can be defined to. ! The function names are operator followed by the. ! Otherwise they are like normal member functions:

Overloading Operators

! A class in C++ is similar to a structure. ! A class contains members: - variables AND. - public: accessible outside the class.

l A class in C++ is similar to a structure. l A class contains members: - variables AND - public: accessible outside the class.

! Data is stored in variables. - Perhaps using arrays and structs. ! Program is a collection of functions that perform

! Data is stored in variables. - Perhaps using arrays and structs. ! Program is a collection of functions that perform

More About Classes. Gaddis Ch. 14, CS 2308 :: Fall 2015 Molly O'Neil

! A class in C++ is similar to a structure. ! A class contains members: - variables AND. - public: accessible outside the class.

! Data is stored in variables. - Perhaps using arrays and structs. ! Program is a collection of functions that perform

The Class. Classes and Objects. Example class: Time class declaration with functions defined inline. Using Time class in a driver.

! Data is stored in variables. - Perhaps using arrays and structs. ! Program is a collection of functions that perform

! Data is stored in variables. - Perhaps using arrays and structs. ! Program is a collection of functions that perform

l A class in C++ is similar to a structure. - It allows you to define a new (composite) data type. l A class contains the following: - variables AND

l A class in C++ is similar to a structure. - It allows you to define a new (composite) data type. l A class contains the following: - variables AND

! Determine if a number is odd or even. ! Determine if a number/character is in a range. ! Assign a category based on ranges (wind speed)

! Determine if a number is odd or even. ! Determine if a number/character is in a range. - 1 to 10 (inclusive) - between a and z (inclusive)

CAAM 420 Fall 2012 Lecture 29. Duncan Eddy

Agenda. The main body and cout. Fundamental data types. Declarations and definitions. Control structures

CS201- Introduction to Programming Current Quizzes

Practice Problems CS2620 Advanced Programming, Spring 2003

Chapter 6: User-Defined Functions. Objectives (cont d.) Objectives. Introduction. Predefined Functions 12/2/2016

Short Notes of CS201

FORM 2 (Please put your name and form # on the scantron!!!!)

CS201 - Introduction to Programming Glossary By

Unit 1: Preliminaries Part 4: Introduction to the Standard Template Library

Pointers, Dynamic Data, and Reference Types

CS2255 HOMEWORK #1 Fall 2012

Week 3. Function Definitions. Example: Function. Function Call, Return Statement. Functions & Arrays. Gaddis: Chapters 6 and 7.

Week 3. Function Definitions. Example: Function. Function Call, Return Statement. Functions & Arrays. Gaddis: Chapters 6 and 7. CS 5301 Spring 2018

OBJECT-ORIENTED PROGRAMMING CONCEPTS-CLASSES II

Exam 3 Chapters 7 & 9

! A program is a set of instructions that the. ! It must be translated. ! Variable: portion of memory that stores a value. char

Function Overloading

1. The term STL stands for?

III. Classes (Chap. 3)

Outline. 1 About the course

Constants, References

7 TEMPLATES AND STL. 7.1 Function Templates

the gamedesigninitiative at cornell university Lecture 7 C++ Overview

Operator Overloading

Topics. bool and string types input/output library functions comments memory allocation templates classes

Polymorphism. Programming in C++ A problem of reuse. Swapping arguments. Session 4 - Genericity, Containers. Code that works for many types.

C++ Review. CptS 223 Advanced Data Structures. Larry Holder School of Electrical Engineering and Computer Science Washington State University

class Polynomial { public: Polynomial(const string& N = "no name", const vector<int>& C = vector<int>());... };

by Pearson Education, Inc. All Rights Reserved. 2

Implementing Abstract Data Types (ADT) using Classes

Purpose of Review. Review some basic C++ Familiarize us with Weiss s style Introduce specific constructs useful for implementing data structures

CS 251 INTERMEDIATE SOFTWARE DESIGN SPRING C ++ Basics Review part 2 Auto pointer, templates, STL algorithms

Classes. Logical method to organise data and functions in a same structure. Also known as abstract data type (ADT).

Multiple Choice (Questions 1 13) 26 Points Select all correct answers (multiple correct answers are possible)

C++_ MARKS 40 MIN

1/29/2011 AUTO POINTER (AUTO_PTR) INTERMEDIATE SOFTWARE DESIGN SPRING delete ptr might not happen memory leak!

C++ 8. Constructors and Destructors

TEMPLATES AND EXCEPTION HANDLING

l Determine if a number is odd or even l Determine if a number/character is in a range - 1 to 10 (inclusive) - between a and z (inclusive)

ADTs & Classes. An introduction

Templates and Vectors

! A literal represents a constant value used in a. ! Numbers: 0, 34, , -1.8e12, etc. ! Characters: 'A', 'z', '!', '5', etc.

C++ Classes, Constructor & Object Oriented Programming

Programming in C++: Assignment Week 8

CS

CS201 Some Important Definitions

CS2141 Software Development using C/C++ C++ Basics

CSCE 110 PROGRAMMING FUNDAMENTALS

COM S 213 PRELIM EXAMINATION #2 April 26, 2001

Exceptions, Templates, and the STL

Instantiation of Template class

Object Oriented Design

CSC 126 FINAL EXAMINATION Spring Total Possible TOTAL 100

Arrays. Arizona State University 1

Variables. Data Types.

Note 12/1/ Review of Inheritance Practice: Please write down 10 most important facts you know about inheritance...

Homework 5. Yuji Shimojo CMSC 330. Instructor: Prof. Reginald Y. Haseltine

Distributed Real-Time Control Systems. Lecture 17 C++ Programming Intro to C++ Objects and Classes

7.1 Optional Parameters

COMP322 - Introduction to C++ Lecture 02 - Basics of C++

14.1. Chapter 14: static member variable. Instance and Static Members 8/23/2014. Instance and Static Members

Fast Introduction to Object Oriented Programming and C++

OBJECT ORIENTED PROGRAMMING USING C++ CSCI Object Oriented Analysis and Design By Manali Torpe

Lesson 13 - Vectors Dynamic Data Storage

CSI33 Data Structures

Course "Data Processing" Name: Master-1: Nuclear Energy Session /2018 Examen - Part A Page 1

Lecture on pointers, references, and arrays and vectors

POLYMORPHISM 2 PART. Shared Interface. Discussions. Abstract Base Classes. Abstract Base Classes and Pure Virtual Methods EXAMPLE

POLYMORPHISM 2 PART Abstract Classes Static and Dynamic Casting Common Programming Errors

CS Final Exam Review Suggestions - Spring 2014

Homework #3 CS2255 Fall 2012

CS197c: Programming in C++

Arrays. Week 4. Assylbek Jumagaliyev

Lecture 8. Xiaoguang Wang. February 13th, 2014 STAT 598W. (STAT 598W) Lecture 8 1 / 47

Introduction to C++ Systems Programming

C++: Overview and Features

FORM 1 (Please put your name and form # on the scantron!!!!) CS 161 Exam I: True (A)/False(B) (2 pts each):

5. Assuming gooddata is a Boolean variable, the following two tests are logically equivalent. if (gooddata == false) if (!

8. Functions (II) Control Structures: Arguments passed by value and by reference int x=5, y=3, z; z = addition ( x, y );

Introduction to Classes

FORM 1 (Please put your name and section number (001/10am or 002/2pm) on the scantron!!!!) CS 161 Exam II: True (A)/False(B) (2 pts each):

Developed By : Mrs. K. M. Sanghavi

Transcription:

Operator Overloading and Templates Week 6 Gaddis: 8.1, 14.5, 16.2-16.4 CS 5301 Spring 2015 Jill Seaman Linear Search! Search: find a given target item in an array, return the index of the item, or -1 if not found.! Linear Search: Very simple search method: - Compare first element to target value, if not found then compare second element to target value... - Repeat until: target value is found (return its index) or we run out of items (return -1). 1 2 Linear Search in C++ int searchlist (int list[], int size, int target) { int position = -1; for (int i=0; i<size; i++) { //position of target if (list[i] == target) //found the target! position = i; //record which item return position; Is this algorithm correct? How can we make it more efficient? Does the if need an else? 3 Operator Overloading! Operators such as =, +, <, and others can be defined to work for objects of a user-defined class! The name of the function defining the over-loaded operator is operator followed by the operator symbol: operator+ to define the + operator, and operator= to define the = operator! Just like a regular member function: - Prototype goes in the class declaration - Function definition goes in implementation file 4

Overloaded Operator Prototype! Prototype: int operator-(const Time &right); Invoking an Overloaded Operator! Operator can be invoked (called) as a regular member function: int minutes = object1.operator-(object2); return type function name! Pass by constant reference Does NOT copy the argument as pass-by-value does But does not allow the function to change its value (so it s like pass by value without the copying). optional for overloading operators parameter for object on right side of operator 5! It can also be invoked using the more conventional syntax for operators: int minutes = object1 - object2; This is the main reason to overload operators, so you can use this syntax for objects of your class! Both call the same function (operator-), from the perspective of object1 (on the lefthand side). 6 Example class: Time class declaration with functions defined inline Example: minus for Time objects We will use this for operator overloading examples: //new data type int hour; int minute; Time() { hour = 12; minute = 0; Time(int hr,int min) { hour = hr; minute = min; void sethour(int hr) { hour = hr; void setminute(int min) { minute = min; int gethour() const { return hour; int getminute() const { return minute; void display() const { cout << hour << : << minute; ; 7 int hour, minute; int operator- (const Time &right); ; int Time::operator- (const Time &right) { //Note: 12%12 = 0 return (hour%12)*60 + minute - ((right.hour%12)*60 + right.minute); Time time1(12,20), time2(4,40); int minutesdiff = time2 - time1; cout << minutesdiff << endl; Subtraction Output: 260 8

Overloading == and < for Time Overloading + for Time bool Time::operator== (Time right) { if (hour == right.hour && minute == right.minute) return true; else return false; bool Time::operator< (Time right) { if (hour == right.hour) return (minute < right.minute); return (hour%12) < (right.hour%12); Time time1(12,20), time2(12,21); if (time1<time2) cout << correct << endl; if (time1==time2) cout << correct again << endl; 9 int hour, minute; Time operator+ (Time right); ; Time Time::operator+ (Time right) { //Note: 12%12 = 0 int totalmin = (hour%12)*60 + (right.hour%12)*60 + minute + right.minute; int h = totalmin / 60; h = h%12; //keep it between 0 and 11 if (h==0) h = 12; Time result(h, totalmin % 60); return result; Time t1(12,5); Time t2(2,50); Time t3 = t1+t2; t3.display(); //convert 0:xx to 12:xx Output: 2:55 10 The this pointer Overloading Prefix ++ for Time! this: a predefined pointer that can be used in a class s member function definitions! this always points to the instance (object) of the class whose function is being executed.! Use this to access member vars that may be hidden by parameters with the same name: Time::Time(int hour, int minute) { // Time *this; implicit decl this->hour = hour; this->minute = minute;! Or return *this from a function. 11 int hour, minute; Time operator++ (); ; Time Time::operator++ (Time right) { //Note: 12%12 = 0 if (minute == 59) { minute = 0; if (hour == 12) hour = 1; else hour++; else { minute++; return *this; //this points to the calling instance Time t1(12,55); Time t2 = ++t1; Output: 12:56 12:56 t1.display(); cout << ; t2.display(); 12

Templates: Type independence! Many functions, like finding the maximum of an array, do not depend on the data type of the elements.! We would like to re-use the same code regardless of the item type...! without having to maintain duplicate copies: - maxintarray (int a[]; int size) - maxfloatarray (float a[]; int size) - maxchararray (char a[]; int size) 13 Generic programming! Writing functions and classes that are typeindependent is called generic programming.! These functions and classes will have one (or more) extra parameter to represent the specific type of the components.! When the stand-alone function is called the programmer provides the specific type: max<string>(array,size); 14 Templates! C++ provides templates to implement generic stand-alone functions and classes.! A function template is not a function, it is a design or pattern for a function.! The function template makes a function when the compiler encounters a call to the function. - Like a macro, it substitutes appropriate type 15 Example function template swap template <class T> void swap (T &lhs, T &rhs) { T tmp = lhs; lhs = rhs; rhs = tmp; int main() { int x = 5; int y = 7; string a = hello ; string b = there ; swap <int> (x, y); Output: //int replaces Object swap <string> (a, b); //string replaces Object cout << x << << y << endl; cout << a << << b << endl; 7 5 there hello 16

Notes about the example! The header: template <class T> - class is a keyword. You could also use typename:! T is the parameter name. You can call it whatever you like. - it is often capitalized (because it is a type) - names like T and U are often used! The parameter name (T in this case) can be replaced ONLY by a type. Example, class template vector: class decl // A barebones vector ADT Note: not ALL types should be replaced by class vector { the type variable T T* data; //stores data in dynamically allocated array int length; //number of elements in vector vector(); vector(int); ~vector(); int size() const; T getelementat(int k); //access the T in the kth position void setelementat(int k, T v); //set the T in the kth position ; 17 This is similar to the SimpleVector in the Gaddis book. 18 Example, class template vector, function definitions vector<t>::vector() { length = 0; data = NULL; vector<t>::vector(int s) { length = s; data = new T[length]; //note that the elements are not initialized vector<t>::~vector() { delete [] data; 19 Example, class template vector, function definitions int vector<t>::size() const { return length; T vector<t>::getelementat(int k) { assert (k>=0 && k<length); return data[k]; void vector<t>::setelementat(int k, T v) { assert (k>=0 && k<length); data[k]=v; assert(e): if e is false, it causes the execution of the program to stop (exit). Requires #include<cassert> 20

Example, class template using vector int main() { vector<string> m(3); m.setelementat(0, K ); m.setelementat(1, Q"); m.setelementat(2, J"); for (int i=0; i<m.size(); i++) { cout << m.getelementat(i) << endl; Output: K Q J 21 Class Templates and.h files! Template classes cannot be compiled separately - Machine code is generated for a template class only when the class is instantiated (used). When you compile a template (class declarations + functions definitions) it will not generate machine code. - When a file using (instantiating) a template class is compiled, it requires the complete definition of the template, including the function definitions. - Therefore, for a class template, the class declaration AND function definitions must go in the header file. - It is still good practice to define the functions outside 22 of (after) the class declaration. Sample Problem 1 Sample Problem 2 FeetInches Modification: Modify the FeetInches class discussed in this chapter so it overloads the following operators: <= >=!= Demonstrate the class s capabilities in a simple program. SimpleVector Modification: Modify the SimpleVector class template presented in this chapter to include the member functions push_back and pop_back. These functions should emulate the STL vector class member functions of the same name. (See Table 16-5.) The push_back function should accept an argument and insert its value at the end of the array. The pop_back function should accept no argument and remove the last element from the array. Both of these should change the size of the vector appropriately. Test the class with a driver program. 23 24