Monday, Feb 10, 2003Kate Gregory with material from Deitel and Deitel Week 6 Lab 2 is marked Hand in Lab 3 Questions from Last Week Operator Overloading.

Slides:



Advertisements
Similar presentations
Chapter 17 vector and Free Store John Keyser’s Modifications of Slides By Bjarne Stroustrup
Advertisements

Introduction to Programming Lecture 39. Copy Constructor.
Monday, Mar 24, 2003Kate Gregory with material from Deitel and Deitel Week 11 Exceptions.
Lecture 3 Feb 4 summary of last week’s topics and review questions (handout) Today’s goals: Chapter 1 overview (sections 1.4 to 1.6) c++ classes constructors,
Rossella Lau Lecture 10, DCO10105, Semester B, DCO10105 Object-Oriented Programming and Design  Lecture 10: Operator overload  Operator overload.
 2006 Pearson Education, Inc. All rights reserved Operator Overloading.
Class template Describing a generic class Instantiating classes that are type-specific version of this generic class Also are called parameterized types.
Operator Overloading in C++ Systems Programming. Systems Programming: Operator Overloading 22   Fundamentals of Operator Overloading   Restrictions.
Rossella Lau Lecture 8, DCO10105, Semester B, DCO10105 Object-Oriented Programming and Design  Lecture 8: Polymorphism & C++ pointer  Inheritance.
Class Array template The array class defined in last week manipulate array of integer If we need to define class of array for float, double data type,
 2000 Prentice Hall, Inc. All rights reserved. Chapter 18 - Operator Overloading Outline 18.1Introduction 18.2Fundamentals of Operator Overloading 18.3Restrictions.
Operator Overloading and Memory Management. Objectives At the conclusion of this lesson, students should be able to: Overload C++ operators Explain why.
CS-2303 System Programming Concepts
More Classes in C++ Bryce Boe 2012/08/20 CS32, Summer 2012 B.
Operator Overloading in C++
Review of C++ Programming Part II Sheng-Fang Huang.
Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 19 Clicker Questions November 3, 2009.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 14: Pointers, Classes, Virtual Functions, and Abstract Classes.
The Rest of the Story.  Constructors  Compiler-generated  The Initializer List  Copy Constructors  Single-arg (conversion ctors)  The Assignment.
 200 Total Points ◦ 74 Points Writing Programs ◦ 60 Points Tracing Algorithms and determining results ◦ 36 Points Short Answer ◦ 30 Points Multiple Choice.
Monday, Jan 13, 2003Kate Gregory with material from Deitel and Deitel Week 2 Questions from Last Week Control Structures Functions Lab 1.
Operator Overloading Version 1.0. Objectives At the end of this lesson, students should be able to: Write programs that correctly overload operators Describe.
Chapter 13. Procedural programming vs OOP  Procedural programming focuses on accomplishing tasks (“verbs” are important).  Object-oriented programming.
1 C++ Classes and Data Structures Jeffrey S. Childs Chapter 5 An Array Class Jeffrey S. Childs Clarion University of PA © 2008, Prentice Hall.
1 Data Structures - CSCI 102 CS102 C++ Pointers & Dynamic Objects Prof Tejada.
Pointers OVERVIEW.
Pointers and Dynamic Memory Allocation Copyright Kip Irvine 2003, all rights reserved. Revised 10/28/2003.
Object-Oriented Programming in C++
Current Assignments Start Reading Chapter 6 Project 3 – Due Thursday, July 24 Contact List Program Homework 6 – Due Sunday, July 20 First part easy true/false.
CSC 107 – Programming For Science. The Week’s Goal.
Overloading Operator MySting Example. Operator Overloading 1+2 Matrix M 1 + M 2 Using traditional operators with user-defined objects More convenient.
Monday, Jan 6, 2003Kate Gregory with material from Deitel and Deitel CO 204 Object Oriented Programming 2003 Trent University Kate Gregory.
CS 376b Introduction to Computer Vision 01 / 23 / 2008 Instructor: Michael Eckmann.
Monday, Feb 3, 2003Kate Gregory with material from Deitel and Deitel Week 5 Lab 1 comments Hand in Lab 2 Questions from Last Week Classes continued Lab.
 2000 Deitel & Associates, Inc. All rights reserved. Chapter 12 - Templates Outline 12.1Introduction 12.2Function Templates 12.3Overloading Template Functions.
Lecture 3 Classes, Structs, Enums Passing by reference and value Arrays.
CPSC 252 The Big Three Page 1 The “Big Three” Every class that has data members pointing to dynamically allocated memory must implement these three methods:
CMSC 202, Version 3/02 1 Copy Constructors and Overloaded Assignment.
 140 Total Points ◦ 100 Points Writing Programs ◦ 24 Points Tracing Algorithms and determining results ◦ 16 Points Short Answer  Similar to quizzes.
1 Today’s Objectives  Announcements Homework #3 is due on Monday, 10-Jul, however you can earn 10 bonus points for this HW if you turn it in on Wednesday,
Operator Overloading. Binary operators Unary operators Conversion Operators –Proxy Classes bitset example Special operators –Indexing –Pre-post increment/decrement.
By Joaquin Vila Prepared by Sally Scott ACS 168 Problem Solving Using the Computer Week 13 More on Classes Chapter 8 Week 13 More on Classes Chapter 8.
CS-1030 Dr. Mark L. Hornick 1 Basic C++ State the difference between a function/class declaration and a function/class definition. Explain the purpose.
Programming Languages and Paradigms C++. C++ program structure  C++ Program: collection of files Header files CPP source files  Files contain class,
1 Becoming More Effective with C++ … Day Two Stanley B. Lippman
Programming Fundamentals. Topics to be covered Today Recursion Inline Functions Scope and Storage Class A simple class Constructor Destructor.
1 Classes II Chapter 7 2 Introduction Continued study of –classes –data abstraction Prepare for operator overloading in next chapter Work with strings.
Object-Oriented Programming in C++ Lecture 4 Constants References Operator overloading.
Engineering Classes. Objectives At the conclusion of this lesson, students should be able to: Explain why it is important to correctly manage dynamically.
Chapter 1 C++ Basics Review (Section 1.4). Classes Defines the organization of a data user-defined type. Members can be  Data  Functions/Methods Information.
1 Chapter 15-1 Pointers, Dynamic Data, and Reference Types Dale/Weems.
Monday, Jan 27, 2003Kate Gregory with material from Deitel and Deitel Week 4 Questions from Last Week Hand in Lab 2 Classes.
Memory Management.
Yan Shi CS/SE 2630 Lecture Notes
Overloading C++ supports the concept of overloading Two main types
Pointers and Dynamic Arrays
Copy Constructor / Destructors Stacks and Queues
Chapter 15 Pointers, Dynamic Data, and Reference Types
Operator Overloading; String and Array Objects
Chapter 15 Pointers, Dynamic Data, and Reference Types
CISC/CMPE320 - Prof. McLeod
9-10 Classes: A Deeper Look.
Operator Overloading; String and Array Objects
Chapter 18 - Operator Overloading
Pointers and References
ENERGY 211 / CME 211 Lecture 17 October 29, 2008.
9-10 Classes: A Deeper Look.
Presentation transcript:

Monday, Feb 10, 2003Kate Gregory with material from Deitel and Deitel Week 6 Lab 2 is marked Hand in Lab 3 Questions from Last Week Operator Overloading Lab 4

Monday, Feb 10, 2003Kate Gregory with material from Deitel and Deitel Schedule

Monday, Feb 10, 2003Kate Gregory with material from Deitel and Deitel Stack vs. Heap Allocate on the stack: if (x > 0) { Rectangle r(3,4); cout << r.area(); } Object exists only while execution is between the brace brackets

Monday, Feb 10, 2003Kate Gregory with material from Deitel and Deitel Stack vs. Heap Allocate on the heap: if (x > 0) { Rectangle* pr = new Rectangle(3,4); cout area(); } Object continues to exist until it is deleted If you plan to save a pointer and use it elsewhere, it must point to a location on the heap

Monday, Feb 10, 2003Kate Gregory with material from Deitel and Deitel Gets and Sets class BankAccount { private: int balance; //in pennies public: int getbalance() {return balance;} void setbalance(int bal) {balance = bal;} // other stuff };

Monday, Feb 10, 2003Kate Gregory with material from Deitel and Deitel Encapsulation to the Rescue class BankAccount { private: float dollarbalance; //in dollars public: int getbalance() {return (int) (dollarbalance*100);} void setbalance(int bal) {dollarbalance = bal/100.0;} // other stuff };

Monday, Feb 10, 2003Kate Gregory with material from Deitel and Deitel Overloading Revisited When a two functions have the same name, they are overloaded class foo { public: int something(int x); int something(); };

Monday, Feb 10, 2003Kate Gregory with material from Deitel and Deitel Operator Overloading All languages have operator overloading int x = 1 + 1; float f = ; Usually, the compiler is the only one who “gets to play”

Monday, Feb 10, 2003Kate Gregory with material from Deitel and Deitel Operator Overloading How do you compare two objects? Date d1, d2; // they get values somehow if (d1.equals(d2)) { // something }

Monday, Feb 10, 2003Kate Gregory with material from Deitel and Deitel Operator Overloading Wouldn’t this be nicer? Date d1, d2; // they get values somehow if (d1 == d2) { // something }

Monday, Feb 10, 2003Kate Gregory with material from Deitel and Deitel Operator Overloading How about this? Date d1, d2; // they get values somehow if (d1 != d2) { d1 = d2 + 3; }

Monday, Feb 10, 2003Kate Gregory with material from Deitel and Deitel How do you overload an operator? You write a function The name is operator followed by the symbol operator+ operator==

Monday, Feb 10, 2003Kate Gregory with material from Deitel and Deitel Where does the function go? For binary operators: class A, B; A a; B b; // give them values somehow int x = a + b;

Monday, Feb 10, 2003Kate Gregory with material from Deitel and Deitel Operator Overload as Member Function // in A.h class A { // whatever else it has int operator+(B b); }; // in A.cpp int A::operator+(B b) { // something }

Monday, Feb 10, 2003Kate Gregory with material from Deitel and Deitel Operator Overload as Global Function // not in any class int operator+(A a, B b); Typically the declaration is in the header file for A and the implementation is in the implementation file for A

Monday, Feb 10, 2003Kate Gregory with material from Deitel and Deitel Operator Overload as Global Function // in A.h class A { // whatever else it has }; int operator+(A a, B b); // in A.cpp int operator+(A a, B b) { // something }

Monday, Feb 10, 2003Kate Gregory with material from Deitel and Deitel Your class isn’t always on the left class A; A a; int x = A + 2; int y = 2 + A; What functions does the compiler look for?

Monday, Feb 10, 2003Kate Gregory with material from Deitel and Deitel Your class on the left int x = A + 2; A::operator+(int i) operator+(A a, int i) The choice is yours

Monday, Feb 10, 2003Kate Gregory with material from Deitel and Deitel Your class on the right int x = 2 + A; int::operator+(A a) –Not possible! operator+(int i, A a) –Your only choice

Monday, Feb 10, 2003Kate Gregory with material from Deitel and Deitel Coding a Global Operator Sometimes it’s easy: class A { private: int x; public: int operator+(int arg); //other stuff }; int operator+(int arg, A a);

Monday, Feb 10, 2003Kate Gregory with material from Deitel and Deitel Coding a Global Operator Here’s a neat trick int A::operator+(int arg); { return x + arg; } int operator+(int arg, A a); { return a + arg; }

Monday, Feb 10, 2003Kate Gregory with material from Deitel and Deitel Coding a Global Operator Sometimes the operator is not reversible like that The global function will need access to private member variables of the class it works with It needs to be an honourary member of the class –friend

Monday, Feb 10, 2003Kate Gregory with material from Deitel and Deitel Where does the function go? For unary operators: class U; U u1, u2; // give them values somehow u2 = !u1;

Monday, Feb 10, 2003Kate Gregory with material from Deitel and Deitel Operator Overload as Member Function // in U.h class U { // whatever else it has U operator!(); }; // in U.cpp U U::operator+() { // something }

Monday, Feb 10, 2003Kate Gregory with material from Deitel and Deitel Operator Overload as Global Function // in U.h class U { // whatever else it has }; U operator!(U u); // in U.cpp U operator!(U u) { // something }

Monday, Feb 10, 2003Kate Gregory with material from Deitel and Deitel What can you overload? Binary + - * / % += -= *= /= %= (pre and post) ^ & | > = <= == != []

Monday, Feb 10, 2003Kate Gregory with material from Deitel and Deitel What can you overload? Unary + - ! Some other scary ones eg &

Monday, Feb 10, 2003Kate Gregory with material from Deitel and Deitel Operator Consistency Operator+ should do something that feels like adding –Matrix add, complex number add –Container (list, queue) add an element –String concatenate –Increase date Don’t mess with people’s heads

Monday, Feb 10, 2003Kate Gregory with material from Deitel and Deitel Operator Consistency If you have defined similar operators, they should work the same way. These three expressions should all have the same result: A a; a = a + 1; a += 1; a++;

Monday, Feb 10, 2003Kate Gregory with material from Deitel and Deitel Tip Use one operator to implement the others: bool A::operator==(const A& arg) { // whatever } bool A::operator!=(const A& arg) { return !(*this == arg); }

Monday, Feb 10, 2003Kate Gregory with material from Deitel and Deitel More Rules You can’t change the order of operations You can’t invent new operators, including unary versions of binary-only operators such as /. You can’t overload operators that work on only fundamental types: int operator+(int i, int j)

Monday, Feb 10, 2003Kate Gregory with material from Deitel and Deitel Overloading << cout << “my number is “ << 3 << endl; Employee e; cout << e << endl; Compiler is looking for ostream& operator<<(ostream& o, Employee e) Typically the code is just like a display() function Return the ostream& that was passed

Monday, Feb 10, 2003Kate Gregory with material from Deitel and Deitel Simple Array Class Implement an Array class with –Range checking –Array assignment –Arrays that know their size –Outputting entire arrays with << –Array comparisons with == and != –Element access with []

Monday, Feb 10, 2003Kate Gregory with material from Deitel and Deitel array.h class Array { friend ostream& operator<<( ostream& o, const Array& a); public: Array( int size = 10 ); Array( const Array& a); //copy constructor ~Array(); int getSize() const { return size; } const Array& operator=( const Array& a); bool operator==( const Array& a) const; bool operator!=( const Array& right ) const { return !( *this == right ); } int& operator[]( int ); const int& operator[]( int ) const; private: int size; int* ptr; // pointer to actual content };

Monday, Feb 10, 2003Kate Gregory with material from Deitel and Deitel Using the Array class int main() { Array integers1(7), integers2; cout << "integers1:" << integers1 << endl; cout << "integers2:" << integers2 << endl; integers1[5] = 1000; cout << integers1[5] << endl; if ( integers1 == integers2 ) cout << "They are equal\n\n"; else cout << "They are not equal\n"; return 0; }

Monday, Feb 10, 2003Kate Gregory with material from Deitel and Deitel Implementing Array - constructor Array::Array( int arraySize ) { size = ( arraySize > 0 ? arraySize : 10 ); ptr = new int[ size ]; for ( int i = 0; i < size; i++ ) ptr[ i ] = 0; }

Monday, Feb 10, 2003Kate Gregory with material from Deitel and Deitel Implementing Array - destructor Array::~Array() { delete [] ptr; } Whenever your destructor does something destructive, you must code a copy constructor and an assignment operator

Monday, Feb 10, 2003Kate Gregory with material from Deitel and Deitel Destructive Destructors Not all classes have a destructor that actually cleans up –Free memory –Close file –Release lock or database connection or... When the destructor cleans up you need to be sure it will never go off accidentally

Monday, Feb 10, 2003Kate Gregory with material from Deitel and Deitel Shallow and Deep Copies An object holds a resource (pointer to memory, name of file, pointer to connection object) If you copy the object bit-for-bit, now two objects hold the same pointer (or handle or name or whatever) When one goes out of scope, the destructor cleans up –The other has a pointer to nowhere!

Monday, Feb 10, 2003Kate Gregory with material from Deitel and Deitel Implementing Array – copy constructor Array::Array( const Array& init ) : size( init.size ), ptr(new int[init.size]) { for ( int i = 0; i < size; i++ ) ptr[i] = init.ptr[i]; }

Monday, Feb 10, 2003Kate Gregory with material from Deitel and Deitel Copy Constructor takes a reference Imagine this code: Array a2(a1); This uses the copy constructor to construct a2 Takes by value: need to make a copy of a1 to pass to the function –Use the copy constructor. –But that takes by value, so need to make a copy Use the copy constructor...

Monday, Feb 10, 2003Kate Gregory with material from Deitel and Deitel Implementing Array – assignment operator const Array& Array::operator=( const Array right ) { // always check for self-assignment if ( &right != this ) { if ( size != right.size ) { delete [] ptr; size = right.size; ptr = new int[ size ]; } for ( int i = 0; i < size; i++ ) ptr[ i ] = right.ptr[ i ]; } return *this; // enables x = y = z; }

Monday, Feb 10, 2003Kate Gregory with material from Deitel and Deitel Copy Constructor vs Assignment operator It’s not about whether the = operator is used It’s about whether something is being constructed Array a1(10); Array a2(a1); Array a3 = a2; a1 = a3;

Monday, Feb 10, 2003Kate Gregory with material from Deitel and Deitel Implementing Array – equality test bool Array::operator==( const Array& right ) const { if ( size != right.size ) return false; // arrays of different sizes for ( int i = 0; i < size; i++ ) if ( ptr[ i ] != right.ptr[ i ] ) return false; // arrays are not equal return true; // arrays are equal }

Monday, Feb 10, 2003Kate Gregory with material from Deitel and Deitel Implementing Array – element access int& Array::operator[]( int subscript ) { if( subscript >= 0 && subscript < size ); return ptr[ subscript ]; else // should throw exception or something exit(1); } Why does it return a reference? integers1[5] = 1000;

Monday, Feb 10, 2003Kate Gregory with material from Deitel and Deitel Implementing Array const int& Array::operator[]( int subscript ) const { if( subscript >= 0 && subscript < size ); return ptr[ subscript ]; // const reference else // should throw exception or something exit(1); } For use with const arrays (since it’s const) Guarantees the object will stay const by not providing a reference to the inside, which could be changed.

Monday, Feb 10, 2003Kate Gregory with material from Deitel and Deitel Implementing Array ostream& operator<<( ostream& output, const Array& a ) { int i; for ( i = 0; i < a.size; i++ ) { output << a.ptr[i] << endl; } return output; //enables cout << x << y; }

Monday, Feb 10, 2003Kate Gregory with material from Deitel and Deitel Remember The Requirements Implement an Array class with –Range checking –Array assignment –Arrays that know their size –Outputting entire arrays with << –Array comparisons with == and != –Element access with []

Monday, Feb 10, 2003Kate Gregory with material from Deitel and Deitel For Next class Enjoy Reading Week – see you Feb 24 Read chapter 9 Do Lab 4 Study for Midterm –Feb 24, class time, this room –Will cover everything till today –You may be asked to write code in handwriting –One hour, closed book –Worth 25%