Operator Overloading Mark Hennessy Dept. Computer Science NUI Maynooth C++ Workshop 18 th – 22 nd September 2006.

Slides:



Advertisements
Similar presentations
Engineering Problem Solving With C++ An Object Based Approach Additional Topics Chapter 10 Programming with Classes.
Advertisements

Operator overloading redefine the operations of operators
Chapter 11 Operator Overloading; String and Array Objects Chapter 11 Operator Overloading; String and Array Objects Part I.
Operator Overloading. Introduction Operator overloading –Enabling C++’s operators to work with class objects –Using traditional operators with user-defined.
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 8 - Operator Overloading Outline 8.1 Introduction 8.2 Fundamentals of Operator Overloading 8.3.
Chapter 7 User-Defined Methods. Chapter Objectives  Understand how methods are used in Java programming  Learn about standard (predefined) methods and.
Exceptions, Templates, And The Standard Template Library (STL) Chapter 16.
Chapter 14: Overloading and Templates
Operator Overloading in C++ Systems Programming. Systems Programming: Operator Overloading 22   Fundamentals of Operator Overloading   Restrictions.
CS 117 Spring 2002 Classes Hanly: Chapter 6 Freidman-Koffman: Chapter 10, intro in Chapter 3.7.
CS-341 Dick Steflik Introduction. C++ General purpose programming language A superset of C (except for minor details) provides new flexible ways for defining.
CMSC 2021 Stream I/O Operators and Friend Functions.
Introduction to Classes and Objects CS-2303, C-Term Introduction to Classes and Objects CS-2303 System Programming Concepts (Slides include materials.
Object Oriented Programming C++. ADT vs. Class ADT: a model of data AND its related functions C++ Class: a syntactical & programmatic element for describing.
Object Oriented Programming C++. ADT vs. Class ADT: a model of data AND its related functions C++ Class: a syntactical & programmatic element for describing.
Operator OverloadingCS-2303, C-Term Operator Overloading CS-2303 System Programming Concepts (Slides include materials from The C Programming Language,
Operator Overloading in C++
C++ Functions. 2 Agenda What is a function? What is a function? Types of C++ functions: Types of C++ functions: Standard functions Standard functions.
CSE 332: C++ templates and generic programming I Motivation for Generic Programming in C++ We’ve looked at procedural programming –Reuse of code by packaging.
1 Operator Overloading in C++ Copyright Kip Irvine, All rights reserved. Only students enrolled in COP 4338 at Florida International University may.
Classes Representing Non-Trivial Objects. Problem Write a program that reads a temperature (either Fahrenheit or Celsius), and displays that same temperature.
CSC241 Object-Oriented Programming (OOP) Lecture No. 10.
Case Study - Fractions Timothy Budd Oregon State University.
Operatorsand Operators Overloading. Introduction C++ allows operators to be overloaded specifically for a user-defined class. Operator overloading offers.
C ++ Programming Languages Omid Jafarinezhad Lecturer: Omid Jafarinezhad Fall 2013 Lecture 2 Department of Computer Engineering 1.
C++ History C++ was designed at AT&T Bell Labs by Bjarne Stroustrup in the early 80's Based on the ‘C’ programming language C++ language standardised in.
ADTs and C++ Classes Classes and Members Constructors The header file and the implementation file Classes and Parameters Operator Overloading.
Data Structures Using C++ 2E1 Inheritance An “is-a” relationship –Example: “every employee is a person” Allows new class creation from existing classes.
CPSC 252 Operator Overloading and Convert Constructors Page 1 Operator overloading We would like to assign an element to a vector or retrieve an element.
Classes Representing Non-Trivial Objects. Problem Write a program that reads a temperature (either Fahrenheit or Celsius), and displays that same temperature.
 2008 Pearson Education, Inc. All rights reserved Operator Overloading.
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved More about.
CSE 332: C++ IO We’ve Looked at Basic Input and Output Already How to move data into and out of a program –Using argc and argv to pass command line args.
Chapter 3 Part I. 3.1 Introduction Programs written in C ◦ All statements were located in function main Programs written in C++ ◦ Programs will consist.
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,
Classes & Objects Lecture-6. Classes and Objects A class is a 'blueprint' for all Objects of a certain type (defined by ADT) class defines the attributes.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 25 December 1, 2009.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 15: Overloading and Templates.
CS Class 19 Today  Practice with classes Announcements  Turn in algorithm for Project 5 in class today  Project 5 due 11/11 by midnight – .
CSE 332: C++ pointers, arrays, and references Overview of Pointers and References Often need to refer to another object –Without making a copy of the object.
1 COMS 261 Computer Science I Title: Classes Date: November 9, 2005 Lecture Number: 29.
Manipulator example #include int main (void) { double x = ; streamsize prec = cout.precision(); cout
Learning Objectives Fundamentals of Operator Overloading. Restrictions of Operator Overloading. Global and member Operator. Overloading Stream-Insertion.
72 4/11/98 CSE 143 Abstract Data Types [Sections , ]
Exception Handling How to handle the runtime errors.
Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 6-1 Learning Objectives  Classes  Constructors  Principles of OOP  Class type member.
C++ Features Function Overloading Default Functions arguments Thinking about objects – relationship to classes Types of member functions Constructor and.
Asif Nawaz University Institute of Information Technology, PMAS-AAUR Lecture 07: Object Oriented Programming:2014 Object-Oriented Programming in C++ Operator.
CMSC 202 Lesson 9 Classes III. Warmup Using the following part of a class, implement the Sharpen() method, it removes 1 from the length: class Pencil.
Introduction Every program takes some data as input and generate processed data as out put . It is important to know how to provide the input data and.
Operator Overloading.
Chapter 2 Objects and Classes
CSE1002 – Problem Solving with Object Oriented Programming
Department of Computer and Information Science, School of Science, IUPUI Operator Overloading Dale Roberts, Lecturer Computer Science, IUPUI
Polymorphism in C++ Operator Overloading
Chapter 15: Overloading and Templates
C++ History C++ was designed at AT&T Bell Labs by Bjarne Stroustrup in the early 80's Based on the ‘C’ programming language C++ language standardised in.
The dirty secrets of objects
3.3 Abstract Classes, Assignment, and Casting in a Hierarchy
Operator Overloading; String and Array Objects
Operator Overloading.
Operator Overloading; String and Array Objects
Overview of C++ Overloading
Operator Overloading.
CISC/CMPE320 - Prof. McLeod
Operator Overloading Professor Hugh C. Lauer CS-2303, System Programming Concepts (Slides include materials from The C Programming Language, 2nd edition,
COP 3330 Object-oriented Programming in C++
COMS 261 Computer Science I
Operator Overloading; String and Array Objects
Presentation transcript:

Operator Overloading Mark Hennessy Dept. Computer Science NUI Maynooth C++ Workshop 18 th – 22 nd September 2006

Operator Overloading The compilers built in operator symbols work with classes defined by the programmer. The meaning of an operator may be overloaded (in OO languages), so that its behaviour may be polymorphic i.e. implemented differently for different classes. Overloading operators allow us to give all classes in a system a common interface, allowing us to perform similar operations on a range of different objects.

Assignment Assignment (=) is already overloaded. It has a default behaviour for all objects. It can be overridden for individual classes and not automatically for their descendant classes. The user defined behaviour of any other operator may be inherited by descendant classes.

C++ Syntax Return_type operator symbol(parameter list) Operators which may be overloaded include arithmetic and relational operators. The return type for the boolean operators is a boolean value represented by 1 or 0. Arithmetic operators return type is an object of the same class as other objects in the expression.

The parameter list usually consists of an object of the class, passed by reference rather that by value, to avoid making an unnecessary copy. The const prefix is frequently used to indicate that, although the object has been passed by reference it should not be modified by the method.

Overloading the ‘+’ operator class studentgrade { private: int mathsgrade; int englishgrade; public: studentgrade(); int getmathsgrade(); int getenglishgrade(); void setmathsgrade(int grade_in); void setenglishgrade(int grade_in); };

Adding student grades : Grade 3 = Grade 1 + Grade 2 If we want to add 2 studentgrade objects together we must add the following to the above class: studentgrade operator + (const studentgrade& grade_in); void main() { studentgrade grade_total, student1, student2; grade_total = student1 + student2; }

The operator definition studentgrade studentgrade::operator + (const studentgrade& grade_in) { studentgrade result; result.mathsgrade = mathsgrade + grade_in.mathsgrade; result.englishgrade = englishgrade + grade_in.englishgrade; return result; }

student1 calls the operator method student2 is its argument grade_total is its return value. In main we can reference the components of the object grade_total as follows: grade_total.getmathsgrade() …

Stream Classes A stream is a general name given to a flow of data e.g. cin, cout. In C++ a stream is represented by an object of a particular class. There are no formatting characters in streams, since each object knows how to display itself (due to operator overloading). Existing operators and functions (e.g. insertion >) may be overloaded to work with classes that you create.

Istream & ostream The istream class performs specific input activities or extractions The ostream class handles output or insertion activities To overload the ostream and istream operators we use the following syntax: ostream& operator << (ostream&, class_type&); istream& operator >> (istream&, class_type&); where class_type is a parameter of some user defined class, passed by reference. The method returns a reference to an ostream / istream object, and also takes one as parameter.

class person{ private: char name[20]; int age; public: char* getname(); int getage(); void setname(char * name_in); void setage(int age_in); };

Main In main a person is input / output using cin and cout void main() { person p; … cout << p; }

Overloading << std::ostream& operator << (std::ostream& out, person& person) {return out << “Name”<< person.getname() <<endl <<”Age” << person.getage() <<endl; }

Exception Handling C++ Syntax try {/* some code */ } catch (…) { /* any exception */ }

An Exception Class #include class MException { public: MException() {} MException(std::string The_Message): message(The_message) {} std::string get_message() const; private: std::string The_message; };

Using Exceptions #include #include “MException.h”/* Include MException */ int main(int argc, char * argv[]) { try { if (argc == 1)/* No args */ throw MException(“No Args!”); } catch (MException me) { std::cout<<me.get_message()<<“\n”; }