Function Overloading

Similar documents
Overloading Operators in C++

Scope. Scope is such an important thing that we ll review what we know about scope now:

Implementing an ADT with a Class

Object Oriented Design

Polymorphism Part 1 1

Roxana Dumitrescu. C++ in Financial Mathematics

3.Constructors and Destructors. Develop cpp program to implement constructor and destructor.

Fast Introduction to Object Oriented Programming and C++

CS32 - Week 4. Umut Oztok. Jul 15, Umut Oztok CS32 - Week 4

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

Introduction to Classes

CSCE 110 PROGRAMMING FUNDAMENTALS

Lab 2: ADT Design & Implementation

Ch02. True/False Indicate whether the statement is true or false.

Chapter 13: Introduction to Classes Procedural and Object-Oriented Programming

Introduction to C++ Systems Programming

What is Polymorphism? Quotes from Deitel & Deitel s. Why polymorphism? How? How? Polymorphism Part 1

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

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

CSC1322 Object-Oriented Programming Concepts

C:\Temp\Templates. Download This PDF From The Web Site

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

Interview Questions of C++

Cpt S 122 Data Structures. Introduction to C++ Part II

Welcome Back. CSCI 262 Data Structures. Hello, Let s Review. Hello, Let s Review. How to Review 8/19/ Review. Here s a simple C++ program:

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

Introduction Of Classes ( OOPS )

CS201 Some Important Definitions

Introducing C++ to Java Programmers

(5 2) Introduction to Classes in C++ Instructor - Andrew S. O Fallon CptS 122 (February 7, 2018) Washington State University

Lecture 5. Function Pointers

CHAPTER 1 Introduction to Computers and Programming CHAPTER 2 Introduction to C++ ( Hexadecimal 0xF4 and Octal literals 031) cout Object

7.1 Optional Parameters

Short Notes of CS201

Welcome Back. CSCI 262 Data Structures. Hello, Let s Review. Hello, Let s Review. How to Review 1/9/ Review. Here s a simple C++ program:

Government Polytechnic, Muzaffarpur. Name of the Lab: OBJECT ORIENTED PROGRAMMING

Operator overloading

CS201 - Introduction to Programming Glossary By

More Functions. Pass by Value. Example: Exchange two numbers. Storage Classes. Passing Parameters by Reference. Pass by value and by reference

PIC 10A Objects/Classes

Object-Oriented Design (OOD) and C++

C++ Mini Lessons Last Update: Feb 7, 2018

Constructor - example

Object-Oriented Programming

Module Operator Overloading and Type Conversion. Table of Contents

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

Midterm Review. PIC 10B Spring 2018

AN OVERVIEW OF C++ 1

Lesson 13 - Vectors Dynamic Data Storage

Chapter 9 Classes : A Deeper Look, Part 1

CS3157: Advanced Programming. Outline

TEMPLATE IN C++ Function Templates

ADTs in C++ In C++, member functions can be defined as part of a struct

C How to Program, 6/e, 7/e

CAAM 420 Fall 2012 Lecture 29. Duncan Eddy

III. Classes (Chap. 3)

Chapter 2. Procedural Programming

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:

2 2

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

Instantiation of Template class

2 ADT Programming User-defined abstract data types

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

A brief introduction to C++

Recharge (int, int, int); //constructor declared void disply();

CS201- Introduction to Programming Current Quizzes

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

OBJECT ORIENTED PROGRAMMING

CSCI 123 Introduction to Programming Concepts in C++

Lecture 7. Log into Linux New documents posted to course webpage

Abstraction in Software Development

Cpt S 122 Data Structures. Course Review Midterm Exam # 2

COEN244: Class & function templates

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

Increases Program Structure which results in greater reliability. Polymorphism

Implementing Abstract Data Types (ADT) using Classes

CMSC 341 Lecture 6 Templates, Stacks & Queues. Based on slides by Shawn Lupoli & Katherine Gibson at UMBC

Classes. Christian Schumacher, Info1 D-MAVT 2013

And Even More and More C++ Fundamentals of Computer Science

Object Oriented Design Final Exam (From 3:30 pm to 4:45 pm) Name:

Classes: Member functions // classes example #include <iostream> using namespace std; Objects : Reminder. Member functions: Methods.

Class and Function Templates

ADTs & Classes. An introduction

Inheritance, and Polymorphism.

Come and join us at WebLyceum

Motivation for Templates. Class and Function Templates. One Way to Look at Templates...

SRM ARTS AND SCIENCE COLLEGE SRM NAGAR, KATTANKULATHUR

Paytm Programming Sample paper: 1) A copy constructor is called. a. when an object is returned by value

CSI33 Data Structures

CPSC 427: Object-Oriented Programming

C++ PROGRAMMING LANGUAGE: CLASSES. CAAM 519, CHAPTER 13

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

Templates (again) Professor Hugh C. Lauer CS-2303, System Programming Concepts

PIC 10A. Lecture 17: Classes III, overloading

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

Computational Physics

Come and join us at WebLyceum

Modern C++ for Computer Vision and Image Processing. Igor Bogoslavskyi

Programming C++ Lecture 3. Howest, Fall 2012 Instructor: Dr. Jennifer B. Sartor

Operator Overloading in C++ Systems Programming

Transcription:

Function Overloading C++ supports writing more than one function with the same name but different argument lists How does the compiler know which one the programmer is calling? They have different signatures A function s signature is a combination of its name and its argument list the return type is not part of the signature so you can t overload just by changing return type 1

When you use function overloading, ambiguity can happen in 3 cases: 1. if you have call by reference and call by value with the same parameters types: void square (double& x) { x = x * x; void square (double x) { cout << x * x; 2. if there is no matching parameter type for a called function but variables can be automatically converted to appropriate types: int area (int height, int width) { return height * width; double area (double height, double width) { return height * width; 3. if you use default arguments: prototypes: void fcn(int a, int b = 9, double c = 1.33); void fcn(int a, int b); 2

Function Overloading (cont.) Suppose that we have a scenario such as: void swap (int *a, int *b); void swap (double *x, double *y); void swap (bool *p, bool *q); int main() { int i = 4, j = 6; double c = 13.2, d = 43.1; bool flag1 = TRUE, flag2 = FALSE; swap (&i, &j); swap (&c, &d); swap (&flag1, &flag2); with function definitions as shown on the next slide: 3

void swap (int *a, int *b) { int temp; temp = *a; *a = *b; *b = temp; void swap (double *x, double *y) { double temp; temp = *x; *x = *y; *y = temp; void swap (bool *p, bool *q) { bool temp; temp = *p; *p = *q; *q = temp; Each of these functions expects to see pointers as arguments the only difference is what kind of thing the pointer argument is pointing to The compiler matches up the signature in the function definition with the call so that the correct version gets invoked 4

Remember Function Templates No need for 3 different functions We could create a function template definition for swap the function template sets up the framework for the functions we need, then based on how the template is called, the compiler generates the necessary code Example: template <typename T> void swap(t *a, T *b) { T temp; temp = *a; *a = *b; *b = temp; the keyword template tells the compiler it s a function template this is the function s return type here it is void because the original swap functions had void return type everywhere a T occurs in the template, the compiler will substitute the correct type depending on the call to the function 5

One More (trivial) Template Example - template <class T> T square (T x) { return x * x; if called with an int argument, this will return an int result; if called with a double argument, it will return a double. 6

Object Oriented Design Where do we stand now? We ve talked about classes and their definition class definition in <classname>.h file this defines the interfaces for the class implementation of the methods in <classname>.cpp file We ve talked about constructors and destructors default constructor and overloaded constructors issues to consider when a class has a member that is dynamic order of method invocation as a program runs (explored through a trace of what happens in an example using the point class) We discussed copy constructors and saw an example 7

Just to remind you: Constructors: What Happens by Default If you do not define a constructor, the system will define a default constructor the default constructor is supposed to initialize all numeric types to 0, all pointers to null, and all Boolean types to false (but be careful check that it really does this!) If you do define a constructor, yours will be used whenever an object of this type is instantiated that is, whenever an object is declared or new or gcnew is called to create an object of this type If you provide a constructor that takes a nonvoid parameter, you must also provide a default constructor. objects of managed classes must always be declared as tracking handles (otherwise you ll get a compile error) 8

Destructors: What Happens by Default A destructor is a function that: Is automatically invoked when an object is destroyed i.e. at the end of the block in which an object was declared Performs termination housekeeping In particular, it recovers memory to be reused On block exit, destructors for objects declared in the block are called in reverse order of object instantiation (see class example) Takes no arguments and returns no value Has the same name as the class preceded by a ~ There is only one destructor for a class no overloading is possible The system automatically generates a destructor for a class, but Programmers do have to write a destructor when their class dynamically allocates memory (which can happen when data members are pointers or array names or CLI objects) 9

= Operators: What Happens by Default Ordinarily, the compiler will generate a default assignment operator a point class (that has two double data members) is an example of a case in which the = operator is automatically overloaded by the compiler If you define any assignment operator that takes the class as a parameter, the compiler cannot generate a default assignment operator for that class. In these cases, you have to provide an overloaded assignment operator 10

Why do we need a copy constructor? If a copy constructor is missing (for any class), the compiler creates a default one that performs member-by-member copying. For classes that have dynamic members, we need to have appropriate memberwise copy functions (we ve seen an example of why) Let s revisit the class MemberInfo that we looked at before We re going to look at 4 different ways to represent the same information then consider how statements execute differently (and why) 11

#pragma once #ifndef MEMB1 #define MEMB1 using namespace System; Class MemberInfo header: ref class MemberInfo{ public: MemberInfo(); MemberInfo(MemberInfo %); void entername(); void enterage(); String^ getname(); int getage(); void setname(string^); void setage(int); void display(); ~MemberInfo(); private: String ^name; int age; static int count; ; #endif // default constructor // copy constructor // method for entering name // method for entering age // method for extracting name // method for extracting age // method for setting name to a value // method for setting age to a value // method for display of the object s data // destructor 12

// MANAGED CLASS ref class MemberInfo{ public: static int count; MemberInfo(); MemberInfo(MemberInfo %); void entername(); void enterage(); String^ getname(); int getage(); void setname(string^); void setage(int); void display(); ~MemberInfo(); private: String ^name; int age; ; M_Info // STANDARD C++ CLASS // copy constructor w/ ref parameter class MemberInfo{ public: static int count; MemberInfo(); MemberInfo(MemberInfo &); void entername(); void enterage(); string* getname(); int getage(); void setname(string*); void setage(int); void display(); ~MemberInfo(); private: string * name; int age; ; Native M_Info2

// STANDARD C++ CLASS // pointer to string type data member class MemberInfo{ public: static int count; // STANDARD C++ CLASS // string type data member class MemberInfo{ public: static int count; private: ; MemberInfo(); MemberInfo(MemberInfo *); void entername(); void enterage(); string* getname(); int getage(); void setname(string*); void setage(int); void display(); ~MemberInfo(); string * name; int age; private: ; MemberInfo(); MemberInfo(MemberInfo &); void entername(); void enterage(); string getname(); int getage(); void setname(string); void setage(int); void display(); ~MemberInfo(); string name; int age; Native M_Info1 Native M_Info

What happens with = and ==? M_Info Has members MemberInfo(MemberInfo %); String ^name; Does not allow this sequence of statements MemberInfo ^n1, ^n2; *n1 = *n2; // error C2582: 'operator =' function is unavailable Allows this sequence of statements: if (n1 == n2) cout << "equal \n"; Native M_Info Has members MemberInfo(MemberInfo &); string name; Allows this sequence of statements: MemberInfo *n1, *n2; *n1 = *n2; Does not allow if (n1 == n2) cout << "equal \n"; Why should this allow ==? Executes the default assignment operator // error C2678: binary '==' : no operator found which takes a left-hand operand of type 'MemberInfo' (or there is no acceptable conversion)

What happens with = and ==? Native M_Info 1 Has members MemberInfo(MemberInfo *); string * name; int age; Allows MemberInfo *n1, *n2; *n1 = *n2; if (n1 == n2) cout << "equal \n"; Native M_Info 2 Has members MemberInfo(MemberInfo &); string* name; int age; Allows MemberInfo *n1, *n3; *n1 = *n3; if (n1 == n3) cout << "equal \n"; Why should this allow assignment and ==? Why should this allow assignment and ==? Moral of the story: Be sure you know what = (assignment) and == (equality test) really mean for your class!

Overloading Operators in C++ C++ allows the programmer to redefine the function of most built-in operators on a class-by-class basis the operator keyword is used to declare a function that specifies what an operator symbol (such as = or +) means when it is applied to instances of a class this gives the operator more than one meaning, and the compiler determines what meaning is intended by looking at the types of its operands syntax: type operator <operator-symbol> (parameter-list) Example: overloading the addition operator and the assignment operator for a class Complex that is intended to represent complex numbers

Example Class to represent complex numbers: header (class definition file) #pragma once #include <iostream> using namespace System; using namespace std; class Complex { public: Complex (); Complex (double r, double i); Complex operator+ (Complex &other); Complex & Complex::operator = (Complex &n); void display(); private: double re,im; ;

.cpp source (implementation) file for for class Complex #include "stdafx.h" #include " Complex.h" Complex::Complex (){ re = 0.0; im = 0.0; Complex::Complex(double r, double i){ re = r; im = i; Overloaded addition operator Complex Complex::operator + (Complex &other){ return Complex (re + other.re, im + other.im); Complex & Complex::operator = (Complex &n){ re = n.re; im = n.im; return *this; Overloaded assignment operator void Complex::display(){ cout << re << "," << im << endl;

Example of a small program using class Complex: #include "stdafx.h" #include <iostream> #include "Complex.h" using namespace System; using namespace std; int main(array<system::string ^> ^args) { Complex a = Complex(1.2, 3.4); Complex b(3.4, 5.6); Complex c; c = a + b; c.display(); return 0;

Not every operator can be overloaded! Operators that can be overloaded + - * / % ^ & ~! = < > += -= *= /= %= ^= &= = << >> >>= <<= ==!= <= >= && ++ -- ->*, -> [] () new delete new[] delete[] Operators that cannot be overloaded..* ::?: sizeof