Function Overloading I



Similar documents
Operator Overloading. Lecture 8. Operator Overloading. Running Example: Complex Numbers. Syntax. What can be overloaded. Syntax -- First Example

PART-A Questions. 2. How does an enumerated statement differ from a typedef statement?

Comp151. Definitions & Declarations

C++ INTERVIEW QUESTIONS

IS0020 Program Design and Software Tools Midterm, Feb 24, Instruction

CpSc212 Goddard Notes Chapter 6. Yet More on Classes. We discuss the problems of comparing, copying, passing, outputting, and destructing

Storage Classes CS 110B - Rule Storage Classes Page 18-1 \handouts\storclas

C++ Crash Kurs. C++ Object-Oriented Programming

Basics of I/O Streams and File I/O

Class 16: Function Parameters and Polymorphism

Schneps, Leila; Colmez, Coralie. Math on Trial : How Numbers Get Used and Abused in the Courtroom. New York, NY, USA: Basic Books, p i.

More C++ Concepts. Operator overloading Friend Function This Operator Inline Function

13 Classes & Objects with Constructors/Destructors

Name: Class: Date: 9. The compiler ignores all comments they are there strictly for the convenience of anyone reading the program.

MS Visual C++ Introduction. Quick Introduction. A1 Visual C++

A Summary of Operator Overloading

C++FA 5.1 PRACTICE MID-TERM EXAM

Lecture 3. Arrays. Name of array. c[0] c[1] c[2] c[3] c[4] c[5] c[6] c[7] c[8] c[9] c[10] c[11] Position number of the element within array c

Object Oriented Software Design

Simple C++ Programs. Engineering Problem Solving with C++, Etter/Ingber. Dev-C++ Dev-C++ Windows Friendly Exit. The C++ Programming Language

Chapter 5 Functions. Introducing Functions

C++ Input/Output: Streams

Chapter One Introduction to Programming

Compiler Construction

CSI33 Data Structures

! " # $ %& %' ( ) ) *%%+, -..*/ *%%+ - 0 ) 1 2 1

C++ Outline. cout << "Enter two integers: "; int x, y; cin >> x >> y; cout << "The sum is: " << x + y << \n ;

Formatting Numbers with C++ Output Streams

C++ Programming: From Problem Analysis to Program Design, Fifth Edition. Chapter 3: Input/Output

Arrays. number: Motivation. Prof. Stewart Weiss. Software Design Lecture Notes Arrays

Constructor, Destructor, Accessibility and Virtual Functions

Introduction to C++ Introduction to C++ Week 7 Dr Alex Martin 2013 Slide 1

What is a Loop? Pretest Loops in C++ Types of Loop Testing. Count-controlled loops. Loops can be...

UIL Computer Science for Dummies by Jake Warren and works from Mr. Fleming

7.7 Case Study: Calculating Depreciation

Sequential Program Execution

Embedded SQL. Unit 5.1. Dr Gordon Russell, Napier University

Answers to Review Questions Chapter 7

El Dorado Union High School District Educational Services

Object-Oriented Design Lecture 4 CSU 370 Fall 2007 (Pucella) Tuesday, Sep 18, 2007

Ch 7-1. Object-Oriented Programming and Classes

The C++ Language. Loops. ! Recall that a loop is another of the four basic programming language structures

Calling the Function. Two Function Declarations Here is a function declared as pass by value. Why use Pass By Reference?

An Incomplete C++ Primer. University of Wyoming MA 5310

Passing 1D arrays to functions.

C++FA 3.1 OPTIMIZING C++

Data Structures using OOP C++ Lecture 1

Schedule. Structures and Classes in C++ Outline. Goals for This Topic. Another Example of a Structure. What is a Structure? Classes May 12-17, 2005

Member Functions of the istream Class

Object Oriented Software Design II

COSC 181 Foundations of Computer Programming. Class 6

N3458: Simple Database Integration in C++11

COMPUTER SCIENCE 1999 (Delhi Board)

Computer Programming C++ Classes and Objects 15 th Lecture

For the next three questions, consider the class declaration: Member function implementations put inline to save space.

Short Notes on Dynamic Memory Allocation, Pointer and Data Structure

CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013

Moving from C++ to VBA

CS193D Handout 06 Winter 2004 January 26, 2004 Copy Constructor and operator=

Multichoice Quetions 1. Atributes a. are listed in the second part of the class box b. its time is preceded by a colon. c. its default value is

Chapter 3: Writing C# Expressions

Appendix K Introduction to Microsoft Visual C++ 6.0

Chapter 5. Selection 5-1

Introduction to Programming (in C++) Loops. Jordi Cortadella, Ricard Gavaldà, Fernando Orejas Dept. of Computer Science, UPC

Example. Introduction to Programming (in C++) Loops. The while statement. Write the numbers 1 N. Assume the following specification:

Solving Problems Recursively

1. Polymorphism in C++...2

Software Engineering Concepts: Testing. Pointers & Dynamic Allocation. CS 311 Data Structures and Algorithms Lecture Slides Monday, September 14, 2009

Polymorphism. Problems with switch statement. Solution - use virtual functions (polymorphism) Polymorphism

The While Loop. Objectives. Textbook. WHILE Loops

While Loop. 6. Iteration

CISC 181 Project 3 Designing Classes for Bank Accounts

2.2: Bitwise Logical Operations

recursion here it is in C++ power function cis15 advanced programming techniques, using c++ fall 2007 lecture # VI.1

Object Oriented Software Design

Chapter 9 Delegates and Events

PIC 10A. Lecture 7: Graphics II and intro to the if statement

Subject Name: Object Oriented Programming in C++ Subject Code:

Object Oriented Software Design II

Conditions & Boolean Expressions

Lecture 2 Notes: Flow of Control

1. Give the 16 bit signed (twos complement) representation of the following decimal numbers, and convert to hexadecimal:

Basics of C++ and object orientation in OpenFOAM

Common Beginner C++ Programming Mistakes

This loop prints out the numbers from 1 through 10 on separate lines. How does it work? Output:

Java Interview Questions and Answers

F ahrenheit = 9 Celsius + 32

AP Computer Science Java Subset

Subtopics - Functions Function Declaration Function Arguments Return Statements and values. By Hardeep Singh

MAHALAKSHMI ENGINEERING COLLEGE B TIRUCHIRAPALLI

6. Control Structures

UEE1302 (1102) F10 Introduction to Computers and Programming

Compile-time type versus run-time type. Consider the parameter to this function:

Syllabus OBJECT ORIENTED PROGRAMMING C++

Masters programmes in Computer Science and Information Systems. Object-Oriented Design and Programming. Sample module entry test xxth December 2013

Chapter 2: Elements of Java

Handout 1. Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner.

Transcription:

Function Overloading I we can overload functions on their arguments like so: void foo (int iarg) { cout << "Inside foo with int arg: " << iarg << endl; } void foo (double darg) { cout << "Inside foo with double arg: " << darg << endl; } void foo (string sarg) { cout << "Inside foo with string arg: " << sarg << endl; } void foo (int iarg, double darg, string sarg) { cout << "Inside foo with lots of args: " << iarg << ", " << darg << ", " << sarg << endl; } September 1, 2005 c 2005 - Gopi Goswami (goswami@stat.harvard.edu) Page 1

Function Overloading II you can t overload functions on their return values, why? recap: we had two definition of a print( ) function, one for the base class MonteCarloSpecs and another for the derived class MHSpecs here the definition of MHSpecs::print( ) is said to override the definition of MonteCarloSpecs::print( ), its not called function overloading September 1, 2005 c 2005 - Gopi Goswami (goswami@stat.harvard.edu) Page 2

Operator Overloading I the following built-in operators in C++ can be overloaded: unary:!, ++, --, new, delete, new [], delete [], --> etc. binary:!=, <<, >>, ==, <, >, +=, -=, +, -, ( ), [ ] etc. you cannot overload a define a new operator and overload it: e.g. ** cannot be overloaded, you have write a function, say, power for it! operators that can t be overloaded:.,.*, ::,?: September 1, 2005 c 2005 - Gopi Goswami (goswami@stat.harvard.edu) Page 3

Operator Overloading II meaning of a overloaded operator @: (note there is no operator @, its just a dummy symbol, is you like!) if the operator @ has been overloaded as a member function: unary: @obj means a function call obj.operator@( ) binary: obj @ anotherobj means a function call obj.operator@(anotherobj) if the operator @ has been overloaded as a friend function: unary: @obj means a function call operator@(obj) binary: obj @ anotherobj means a function call operator@(obj, anotherobj) September 1, 2005 c 2005 - Gopi Goswami (goswami@stat.harvard.edu) Page 4

Operator Overloading III consider the following declaration: #include <iostream> using std::ostream; class MonteCarloSpecs { friend ostream & operator<< (ostream &outstream, MonteCarloSpecs const &mcs); private: int n_iters; float time_in_secs; float prop_burn_in; double *log_density; public: MonteCarloSpecs (int n_iters, float time_in_secs, float prop_burn_in = 0.05); MonteCarloSpecs (void); int get_n_iters (void) const; void set_n_iters (int n_iters); float get_time_in_secs (void) const; void set_time_in_secs (float time_in_secs); float get_prop_burn_in (void) const; void set_prop_burn_in (float prop_burn_in); void print (void) const; MonteCarloSpecs const & operator= (MonteCarloSpecs const &right); }; September 1, 2005 c 2005 - Gopi Goswami (goswami@stat.harvard.edu) Page 5

Operator Overloading IV what is a friend function? a friend function can access all the non-public members of a class although its not a member function (and hence doesn t need an object to be invoked upon) why consider a friend function at all? for overloading operators << and >> you absolutely need to have a friend function because << and >> take an ostream object (e.g. cout) and istream (e.g. cin) as their first argument hold your breath, lets move on here, we ll uncover the mystery in a bit! in general, use friend functions when you absolutely have to (like the above cases), becuase they violate data hiding September 1, 2005 c 2005 - Gopi Goswami (goswami@stat.harvard.edu) Page 6

Operator Overloading V implementation of a overloaded friend function: ostream & operator<< (ostream &outstream, MonteCarloSpecs const &mcs) { outstream << "This Monte Carlo object:" << endl << "n_iters: " << mcs.get_n_iters( ) << endl << "time_in_secs: " << mcs.get_time_in_secs( ) << endl << "prop_burn_in: " << mcs.get_prop_burn_in( ) << endl << "log_density:" << endl; } int ii; for (ii = 0; ii < mcs.get_n_iters( ) - 1; ++ii) outstream << mcs.log_density[ii] << ", "; outstream << mcs.log_density[ii] << endl; return outstream; September 1, 2005 c 2005 - Gopi Goswami (goswami@stat.harvard.edu) Page 7

Operator Overloading VI when we use cout << mcs1; then we are essentially calling operator<<(cout, mcs1); similarly, cout << mcs1 << mcs2 calls operator<<(operator<<(cout, mcs1), mcs2); thus the comoposition cout << mcs1 << mcs2 is possible because the function operator<<( ) takes cout as the first argument and returns it back! thus operator<<( ) has to be a friend function not a member function September 1, 2005 c 2005 - Gopi Goswami (goswami@stat.harvard.edu) Page 8

Operator Overloading VII implementation a overloaded member function: MonteCarloSpecs const & MonteCarloSpecs::operator= (MonteCarloSpecs const &right) { set_n_iters(right.get_n_iters( )); set_time_in_secs(right.get_time_in_secs( )); set_prop_burn_in(right.get_prop_burn_in( )); for (int ii = 0; ii < get_n_iters( ); ++ii) log_density[ii] = right.log_density[ii]; return *this; } September 1, 2005 c 2005 - Gopi Goswami (goswami@stat.harvard.edu) Page 9

Operator Overloading VIII question is: why can t we declare (and define) the previous function the following way? void operator= (MonteCarloSpecs const &right); to answer it asnwer the following: which of the two delcarations (and hence definitions) would support the following code snippet? MonteCarloSpecs mcs1(10, 10, 0.1); MonteCarloSpecs mcs2(5, 5); MonteCarloSpecs mcs3(30, 30, 0.3); mcs3 = mcs2 = mcs1; note mcs3 = mcs2 = mcs1; means mcs3.operator=(mcs2.operator=(mcs1)), does that help? September 1, 2005 c 2005 - Gopi Goswami (goswami@stat.harvard.edu) Page 10

Operator Overloading IX some quick points, say, we have a class called Foo and a variable Foo foo( ); was created with a constructor with no arguments(, assuming there is one such) the preincrement operator: ++foo; means foo.operator++( ), so the following has to be declared and defined Foo & operator++ (void); the postincrement operator: foo++; means foo.operator++(0), so the following has to be declared and defined Foo operator++ (int dummy); note the int dummy is a flag to help the compiler distinguish between the preincrement and the postincrement operator the preincrement operator returns Foo & it needs returns a reference to *this which is the incremented version the postincrement operator returns Foo it needs returns a copy of the *this which is not incremented yet September 1, 2005 c 2005 - Gopi Goswami (goswami@stat.harvard.edu) Page 11

Operator Overloading X the following type of overloading could be very useful: class PoorlyImplementedNamedList { private: int n_items; double *prices; string *names; public: }; // lots of functions double operator[] (string const name); // lots of functions it could be used as: PoorlyImplementedNamedList pinl; // initialize the list cout << pinl["item1name"] << pinl["item2name"] << endl; September 1, 2005 c 2005 - Gopi Goswami (goswami@stat.harvard.edu) Page 12

Operator Overloading XI the following type of overloading could be very useful: class PoorlyImplementedMatrix { private: int n_rows, n_cols; double **vals; public: }; // lots of functions double operator() (int row, int col); // lots of functions it could be used as: PoorlyImplementedMatrix mm; // initialize the matrix cout << mm(0, 0) << mm(1, 0) << endl; September 1, 2005 c 2005 - Gopi Goswami (goswami@stat.harvard.edu) Page 13

Code Files prog8.h prog8.c prog8makefile September 1, 2005 c 2005 - Gopi Goswami (goswami@stat.harvard.edu) Page 14