Overloading & Polymorphism

Similar documents
Overloaded Operators, Functions, and Students

More Advanced Class Concepts

CS11 Intro C++ Spring 2018 Lecture 5

Vectors of Pointers to Objects. Vectors of Objects. Vectors of unique ptrs C++11. Arrays of Objects

Review. What is const member data? By what mechanism is const enforced? How do we initialize it? How do we initialize it?

Chapter 8. Operator Overloading, Friends, and References. Copyright 2010 Pearson Addison-Wesley. All rights reserved

Overloading Operators in C++

Reference Parameters A reference parameter is an alias for its corresponding argument in the function call. Use the ampersand (&) to indicate that

Abstract Data Types (ADTs) 1. Legal Values. Client Code for Rational ADT. ADT Design. CS 247: Software Engineering Principles

CS 247: Software Engineering Principles. ADT Design

Computer Science II CSci 1200 Lecture 18 Operators and Friends

Operation Overloading.

EINDHOVEN UNIVERSITY OF TECHNOLOGY Department of Mathematics and Computer Science

Ch 8. Operator Overloading, Friends, and References

Program construction in C++ for Scientific Computing

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

The University Of Michigan. EECS402 Lecture 15. Andrew M. Morgan. Savitch Ch. 8 Operator Overloading Returning By Constant Value

Arizona s First University. ECE 373. Operation Overloading. The Revolution Operation Will Be Televised (and, these slides will be online later today)

OBJECT ORIENTED PROGRAMMING USING C++

Object-Oriented Principles and Practice / C++

CSC 330 Object Oriented Programming. Operator Overloading Friend Functions & Forms

Operator overloading. Instructor: Bakhyt Bakiyev

Lecture 3 ADT and C++ Classes (II)

Object oriented programming

UNIT- 3 Introduction to C++

COMP 2355 Introduction to Systems Programming

IS0020 Program Design and Software Tools Midterm, Fall, 2004

KOM3191 Object Oriented Programming Dr Muharrem Mercimek OPERATOR OVERLOADING. KOM3191 Object-Oriented Programming

Operator overloading: extra examples

Ch. 12: Operator Overloading

A <Basic> C++ Course

Operator overloading. Conversions. friend. inline

Introduction to Computers and C++ Programming p. 1 Computer Systems p. 2 Hardware p. 2 Software p. 7 High-Level Languages p. 8 Compilers p.

A <Basic> C++ Course

SFU CMPT Topic: Class Templates

2 ADT Programming User-defined abstract data types

Instantiation of Template class

CISC 2200 Data Structure Fall, C++ Review:3/3. 1 From last lecture:

CS 2704 Spring 2001 February 6, 2001

Shahram Rahatlou. Computing Methods in Physics. Overloading Operators friend functions static data and methods

A linear structure is an ordered (e.g., sequenced) arrangement of elements.

7.1 Optional Parameters

Module Operator Overloading and Type Conversion. Table of Contents

W3101: Programming Languages C++ Ramana Isukapalli

2. Distinguish between a unary, a binary and a ternary operator. Give examples of C++ operators for each one of them.

III. Classes (Chap. 3)

CS105 C++ Lecture 7. More on Classes, Inheritance

A linear structure is an ordered (e.g., sequenced) arrangement of elements.

Review: Exam 1. Your First C++ Program. Declaration Statements. Tells the compiler. Examples of declaration statements

11.2. Overloading Operators

3. Java - Language Constructs I

Stacks and their Applications

Chapter 3. Numeric Types, Expressions, and Output

Motivation for Templates

ADTs & Classes. An introduction

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

Object-Oriented Design (OOD) and C++

Outline. User-dened types Categories. Constructors. Constructors. 4. Classes. Concrete classes. Default constructor. Default constructor

Due Date: See Blackboard

More class design with C++ Starting Savitch Chap. 11

Question: How can we compare two objects of a given class to see if they are the same? Is it legal to do: Rectangle r(0,0,3,3);,, Rectangle s(0,0,4,4)

Operator Overloading

Operator overloading

Makefiles Makefiles should begin with a comment section of the following form and with the following information filled in:

G52CPP C++ Programming Lecture 17

Comp151. Generic Programming: Container Classes

Software Engineering Concepts: Invariants Silently Written & Called Functions Simple Class Example

List, Stack, and Queues

PIC10B/1 Winter 2014 Exam I Study Guide

Engineering Problem Solving with C++, Etter/Ingber

Intermediate Programming & Design (C++) Classes in C++

Week 2: Console I/O and Operators Arithmetic Operators. Integer Division. Arithmetic Operators. Gaddis: Chapter 3 (2.14,3.1-6,3.9-10,5.

CSS 342 Data Structures, Algorithms, and Discrete Mathematics I. Lecture 2. Yusuf Pisan

Programming C++ Lecture 6. Howest, Fall 2013 Instructor: Dr. Jennifer B. Sartor

CS 211 Winter 2004 Sample Final Exam (Solutions)

Operators. Lecture 12 Section Robb T. Koether. Hampden-Sydney College. Fri, Feb 9, 2018

VIRTUAL FUNCTIONS Chapter 10

Operator Overloading

PIC 10A Objects/Classes

CS11 Advanced C++ Spring 2018 Lecture 1

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

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

Review: C++ Basic Concepts. Dr. Yingwu Zhu

the gamedesigninitiative at cornell university Lecture 7 C++ Overview

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

Programming in C++ 5. Integral data types

KEY printed. Do not start the test until instructed to do so! CS 2704 Object-Oriented Software Design and Construction Test 1.

CHAPTER 3 Expressions, Functions, Output

On a 64-bit CPU. Size/Range vary by CPU model and Word size.

Expressions. Arithmetic expressions. Logical expressions. Assignment expression. n Variables and constants linked with operators

Chapter 18 - C++ Operator Overloading

Plan of the day. Today design of two types of container classes templates friend nested classes. BABAR C++ Course 103 Paul F. Kunz

Problem Solving with C++

class Array; // Class template declaration class Array public: // T="type",e.g.,int or float Array(int n); // Create array of n elements Array(); // C

Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur

Introduction to Programming Using Java (98-388)

Friends and Overloaded Operators

Classes and Operators. Ali Malik

Circle all of the following which would make sense as the function prototype.

Friends and Overloaded Operators

Transcription:

Overloading & Polymorphism Overloading is considered ad-hoc polymorphism. 1 Can define new meanings (functions) of operators for specific types. Compiler recognizes which implementation to use by signature (the types of operands used in the expression). Overloading is already supported for many built-in types and operators: 17 * 42 4.3 * 2.9 cout << 79 << 'a' << "overloading is profitable" << endl; The implementation used depends upon the types of operands.

Reasons for Overloading Support natural, suggestive usage: 2 Complex A(4.3, -2.7), B(1.0, 5.8); Complex C; C = A + B; // '+' means addition for this type as well Semantic integrity (assignment for objects with dynamic content must ensure a proper deep copy is made). Uniformity with built-in types (??) Able to use objects in situations expecting primitive values

That Can Be Overloaded Only the following operator symbols can be overloaded: 3 + - * / % ^ & ~! = < > += -= *= /= %= ^= &= = << >> >>= <<= ==!= <= >= && ++ -- ->*, -> [] () new new[] delete delete[] Rule: if you don t know what it means, don t overload it!

Syntax for Overloading 4 Declared and defined like other methods or functions, except that the keyword operator is used. As method of the Name class: bool Name::operator== (const Name& RHS) { return ( (First + Middle + Last) == (RHS.First + RHS.Middle + RHS.Last) ); As nonmember friend function: bool operator==(const Name& LHS, const Name& RHS) { return ( (LHS.First + LHS. Middle + LHS. Last) == (RHS.First + RHS.Middle + RHS.Last) ); It is probably most natural here to use the member operator approach.

Using Overloaded If Name::operator== defined as member function, then nme1 == nme2 is the same as nme1.operator==(nme2) If operator== defined as nonmember function, then nme1 == nme2 With a binary operator, the LHS becomes the implicit object and the RHS the parameter. No self-respecting C++ programmer would use either of these forms. 5 is the same as operator==(nme1, nme2)

Binary Member 6 A class member subtract operator for Complex objects: Complex Complex::operator-(const Complex& RHS) const { return ( Complex(Real - RHS.Real,Imag - RHS.Imag) ); To be a class member, the left operand of an operator must be an object of the class type: Complex X(4.1, 2.3), Y(-1.2, 5.0); OK: X + Y Not OK: cout << X; It is typical to pass by constant reference to avoid the overhead of copying the object.

Binary Non-Member A non-member subtract operator for Complex objects: 7 Complex operator-(const Complex& LHS, const Complex& RHS) { return ( Complex(LHS.getReal() - RHS.getReal(), LHS.getImag() - RHS.getImag()) ); As a non-member, this subtract operator must use the public interface to access the private data members of its parameters unless the class Complex declares it to be a friend. If an operator or function is declared to be a friend of a class then it can access private members as if it were a member function.

Granting an Operator Friend Status 8 Here, the class Complex declares a non-member arithmetic operator to be a friend: class Complex { private: double Real; double Imag; public: Complex(); //... bool operator==(const Complex& RHS) const; //... friend Complex operator*(const Complex& LHS, const Complex& RHS); //... ; The granting of friend status must be in the class declaration. The keyword is NOT also used in the implementation. The declaration of a friend is unaffected by the access controls public and private. Bug note: Visual C++ does not handle friend declarations properly unless Service Pack 4 is installed.

Friend Operator Implementation 9 Here, the class Complex declares a non-member arithmetic operator to be a friend: Complex operator*(const Complex& LHS, const Complex& RHS) { double prodreal = LHS.Real * RHS.Real - LHS.Imag * RHS.Imag; double prodimag = LHS.Real * RHS.Imag + LHS.Imag * RHS.Real; return (Complex(prodReal, prodimag)); The accesses to private data members are now direct, even thoughoperator* is NOT a member of the class Complex. In general, friend status should be granted grudgingly. Most operators should be made members instead. However, this is not always possible

Unary A negation operator for the Complex class: 10 Complex Complex::operator-() const { return ( Complex(-Real, -Imag) ); Note the use of the unary - operator for the built-in type double. Complex A(4.1, 3.2); // A = 4.1 + 3.2i Complex B = -A; // B = -4.1-3.2i Note that a unary member operator takes NO parameters.

Prefix and Postfix 11 A member prefix increment operator for the DisplayableNumber class: DisplayableNumber DisplayableNumber::operator++() { ++Count; return DisplayableNumber(Count, Out); A member postfix increment operator for the DisplayableNumber class: DisplayableNumber DisplayableNumber::operator++(int Dummy) { Count++; return DisplayableNumber(Count-1, Out); The parameter is necessary to make the signature of the postfix operator different from that of the prefix operator. Note the difference in the returned objects.

Multiple Overloading We can have two addition operators in a class: 12 Complex Complex::operator+(double RHS) const { return (Complex(Real + RHS, Imag)); This lets us write mixed expressions, like: Complex X(4.1, 2.3); double R = 1.9; Complex Y = X + R; // Y.Real is 6.0 Signature of function used to resolve which is used: Complex Z = Y + R; // complex plus double Complex W = Y + X; // complex plus complex

Overloading Resolution The compiler looks for a matching implementation of + in this order: 13 Member operator in X of form:?? X::operator +(Y) Nonmember operator of form:?? operator +(X,Y) The return type is not part of the lookup process.

Provide a Reasonable Set of In some cases, whole categories of operators make sense for a type. 14 For instance, it makes sense to overload all of the arithmetic operators for the class Complex. It also makes sense to overload all six relational operators for the class Name. Often the implementation of one operator can "piggyback" off of another: Complex Complex::operator+=(const Complex& RHS) { *this = *this + RHS; // uses overloaded '+' return (*this);

When to use Non-member For operators on primitive data types, such as: Complex operator+(int LHS, const Complex& RHS); 15 When the source for the left operand of a binary operator is not available for modification: E.g., ostream For some type casting operations: E.g., Complex::operator double() const { return ( R );

Stream I/O We do not have access to the istream or ostream class code, so we cannot make overloadings of << or >> members of those classes. 16 We also cannot make them members of a data class because the first parameter must then be an object of that type. Therefore we must define operator<< as non-member function. However, it must access private members of the data class, so we will typically make it a friend of that class. The alternative would be to have accessor functions for all the data members that will be written, and that is frequently unacceptable. The general signature will be: ostream& operator<<(ostream& Out, const Data& towrite);

operator<< for Complex Objects 17 This overloaded operator<< will write a nicely formatted Complex object to any output stream: ostream& operator<<(ostream& Out, const Complex& towrite) { const int Precision = 2; const int FieldWidth = 8; Out << setprecision(precision); Out << setw(fieldwidth) << towrite.real; The formatting settings could also be added as data members of Complex, or if (towrite.imag >= 0) Out << " + "; else Out << " - "; Out << setw(fieldwidth) << fabs(towrite.imag); Out << "i"; Out << endl; return Out;

operator>> for Complex Objects 18 This overloaded operator>> will read a complex number formatted in the manner used by operator<<: istream& operator>>(istream& In, Complex& toread) { char signofimag; In >> toread.real; In >> signofimag; In >> toread.imag; if (signofimag == '-') toread.imag = -toread.imag; In.ignore(1, 'i'); return In; Of course, this depends on knowing exactly how the Complex objects are formatted in the input stream. We could make this a lot more complicated if we had multiple formats to deal with.

An Array Class class Array { private: int Capacity; // dimension of array int Usage; // number of cells in use string* List; // the list void ShiftTailUp(int Start); void ShiftTailDown(int Start); public: Array(int initcapacity = 100, string Init = ""); Array(const Array& Source); Array& operator=(const Array& Source); int getcapacity() const; int getusage() const; bool isfull() const; bool isempty() const; bool Insert(const string& newvalue); //... continues... 19

An Array Class //... continued... bool DeleteAtIndex(int Idx); bool Delete(const string& todel); int Find(const string& tofind) const; string& operator[](int Idx); const string& operator[](int Idx) const; 20 friend ostream& operator<<(ostream& Out, const Array& toprint); ; ~Array();

Overloading operator[] The first overloading of operator[]: 21 string& Array::operator[](int Idx) { assert(0 <= Idx && Idx < Capacity); return List[Idx]; The first is the most commonly used. It provides the functionality you'd normally expect, allowing code like: Array A(10); //... A[5] = "a string"; cout << A[5] << endl; The operator returns a reference to an element of the array, potentially dangerous, but also useful. However, there's an important "gotcha" with the code above

Overloading operator[] The second overloading of operator[]: 22 const string& Array::operator[](int Idx) const { assert(0 <= Idx && Idx < Capacity); return List[Idx]; This is provided only to support cases where a constant return value is required. These are rare. Can you think of one?

Overloading Guidelines Avoid violating expectations about the operator: 23 Complex Complex::operator~() const { return ( Complex(Imag, Real) ); Provide a complete set of properly related operators: a = a + b and a += b have the same effect and it makes sense to support both if either is supplied. Define the operator overload as a class member unless it's necessary to do otherwise. If the operator overload cannot be a class member, then make it a friend rather than add otherwise unnecessary member accessors to the class.