F UNCTION O VERLOADING Chapter 5 Department of CSE, BUET 1.

Slides:



Advertisements
Similar presentations
Constructors and Destructors. Constructor Constructor—what’s this? Constructor—what’s this? method used for initializing objects (of certain class) method.
Advertisements

Constructor. 2 constructor The main use of constructors is to initialize objects. A constructor is a special member function, whose name is same as class.
I NHERITANCE Chapter 7 Department of CSE, BUET 1.
I NTRODUCING O PERATOR O VERLOADING Chapter 6 Department of CSE, BUET 1.
Introduction to Programming Lecture 39. Copy Constructor.
A C LOSER L OOK AT C LASSES 1. A SSIGNING O BJECTS One object can be assigned to another provided that both objects are of the same type. It is not sufficient.
Operator Overloading Fundamentals
A RRAYS, P OINTERS AND R EFERENCES 1. A RRAYS OF O BJECTS Arrays of objects of class can be declared just like other variables. class A{ … }; A ob[4];
V IRTUAL F UNCTIONS Chapter 10 Department of CSE, BUET 1.
Operator Overloading in C++ Systems Programming. Systems Programming: Operator Overloading 22   Fundamentals of Operator Overloading   Restrictions.
Classes: A Deeper Look Systems Programming.
1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation –The new operator –The delete operator –Dynamic.
1 Procedural Concept The main program coordinates calls to procedures and hands over appropriate data as parameters.
Shallow Versus Deep Copy and Pointers Shallow copy: when two or more pointers of the same types point to the same memory – They point to the same data.
Review of C++ Programming Part II Sheng-Fang Huang.
 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.
CS212: Object Oriented Analysis and Design Lecture 12: Operator Overloading-II.
C++ Programming: From Problem Analysis to Program Design, Fifth Edition, Fifth Edition Chapter 7: User-Defined Functions II.
CS212: Object Oriented Analysis and Design Lecture 7: Arrays, Pointers and Dynamic Memory Allocation.
Pointers review Let a variable aa be defined as ‘int *aa;’, what is stored in aa? Let a variable aa be defined as ‘int ** aa;’ what is stored in aa? Why.
ECE122 Feb. 22, Any question on Vehicle sample code?
Classes In C++ 1. What is a class Can make a new type in C++ by declaring a class. A class is an expanded concept of a data structure: instead of holding.
 Classes in c++ Presentation Topic  A collection of objects with same properties and functions is known as class. A class is used to define the characteristics.
Object Oriented Programming Elhanan Borenstein Lecture #3 copyrights © Elhanan Borenstein.
C/C++ 3 Yeting Ge. Static variables Static variables is stored in the static storage. Static variable will be initialized once. 29.cpp 21.cpp.
More C++ Features True object initialisation
 2000 Deitel & Associates, Inc. All rights reserved. Chapter 12 - Templates Outline 12.1Introduction 12.2Function Templates 12.3Overloading Template Functions.
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:
Object-Based Programming Mostly Review. Objects Review what is object? class? member variables? member functions? public members? private members? friend.
Chapter 9 Classes: A Deeper Look, Part I Part II.
CMSC 202, Version 3/02 1 Copy Constructors and Overloaded Assignment.
Chapter 10: Classes and Data Abstraction. Objectives In this chapter, you will: Learn about classes Learn about private, protected, and public members.
A FIRST BOOK OF C++ CHAPTER 6 MODULARITY USING FUNCTIONS.
Data Structures Using C++1 Chapter 3 Pointers and Array-Based Lists.
Functions, Scope, and The Free Store Functions Functions must be declared by a function prototype before they are invoked, return_type Function_name(type,
EEL 3801 C++ as an Enhancement of C. EEL 3801 – Lotzi Bölöni Comments  Can be done with // at the start of the commented line.  The end-of-line terminates.
Chapter 10: Classes and Data Abstraction. Classes Object-oriented design (OOD): a problem solving methodology Objects: components of a solution Class:
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.
Chapter 4: More Object Concepts. Objectives Understand blocks and scope Overload a method Avoid ambiguity Create and call constructors with parameters.
1 // SPECIFICATION FILE (dynarray.h) // Safe integer array class allows run-time specification // of size, prevents indexes from going out of bounds, //
Array and Pointers An Introduction Unit Unit Introduction This unit covers the usage of pointers and arrays in C++
Learners Support Publications Constructors and Destructors.
Constructors And Destructors. 2 Constructor Special Member Function used for Initialization -- Same Name as the Class Name Special Member Function used.
Chapter 12: Pointers, Classes, Virtual Functions, Abstract Classes, and Lists.
Constructors and Destructors
Learning Objectives Pointers as dada members
Chapter 7: User-Defined Functions II
Default Constructors A default constructor is a constructor that takes no arguments. If you write a class with no constructor at all, C++ will write a.
Programming with ANSI C ++
Constructor & Destructor
Class: Special Topics Copy Constructors Static members Friends this
Chapter 6: Functions Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley.
Memberwise Assignment / Initialization
This pointer, Dynamic memory allocation, Constructors and Destructor
Virtual Functions Department of CSE, BUET Chapter 10.
6 Chapter Functions.
CONSTRUCTORS AND DESRUCTORS
Constructors and destructors
Constructors and Destructors
Classes and Objects.
Parameters and Overloading
Java Programming Language
Submitted By : Veenu Saini Lecturer (IT)
A Deeper Look at Classes
ENERGY 211 / CME 211 Lecture 17 October 29, 2008.
Pointers, Dynamic Data, and Reference Types
Constructors & Destructors
SPL – PS3 C++ Classes.
Presentation transcript:

F UNCTION O VERLOADING Chapter 5 Department of CSE, BUET 1

O BJECTIVES Overloading Constructor Functions Creating and Using a Copy Constructor The overload Anachronism (not in syllabus) Using Default Arguments Overloading and Ambiguity Finding the address of an overloaded function 2 Department of CSE, BUET

O VERLOADING C ONSTRUCTOR F UNCTIONS It is possible to overload constructors, but destructors cannot be overloaded. Three main reasons to overload a constructor function To gain flexibility To support arrays To create copy constructors There must be a constructor function for each way that an object of a class will be created, otherwise compile-time error occurs. 3 Department of CSE, BUET

O VERLOADING C ONSTRUCTOR F UNCTIONS ( CONTD.) Let, we want to write MyClass ob1, ob2(10); Then MyClass should have the following two constructors (it may have more) MyClass ( ) { … } MyClass ( int n ) { … } Whenever we write a constructor in a class, the compiler does not supply the default no argument constructor automatically. No argument constructor is also necessary for declaring arrays of objects without any initialization. MyClass array1[5]; // uses MyClass () { … } for each element But with the help of an overloaded constructor, we can also initialize the elements of an array while declaring it. MyClass array2[3] = {1, 2, 3} // uses MyClass ( int n ) { … } for each element 4 Department of CSE, BUET

O VERLOADING C ONSTRUCTOR F UNCTIONS ( CONTD.) Overloading constructor functions also allows the programmer to select the most convenient method to create objects. Date d1(22, 9, 2007); // uses Date( int d, int m, int y ) Date d2(“22-Sep-2007”); // uses Date( char* str ) Another reason to overload a constructor function is to support dynamic arrays of objects created using “new”. As dynamic arrays of objects cannot be initialized, the class must have a no argument constructor to avoid compiler error while creating dynamic arrays using “new”. 5 Department of CSE, BUET

C REATING AND U SING A C OPY C ONSTRUCTOR By default when a assign an object to another object or initialize a new object by an existing object, a bitwise copy is performed. This cause problems when the objects contain pointer to dynamically allocated memory and destructors are used to free that memory. It causes the same memory to be released multiple times that causes the program to crash. Copy constructors are used to solve this problem while we perform object initialization with another object of the same class. MyClass ob1; MyClass ob2 = ob1; // uses copy constructor Copy constructors do not affect assignment operations. MyClass ob1, ob2; ob2 = ob1; // does not use copy constructor 6 Department of CSE, BUET

C REATING AND U SING A C OPY C ONSTRUCTOR ( CONTD.) If we do not write our own copy constructor, then the compiler supplies a copy constructor that simply performs bitwise copy. We can write our own copy constructor to dictate precisely how members of two objects should be copied. The most common form of copy constructor is classname (const classname &obj) { // body of constructor } 7 Department of CSE, BUET

C REATING AND U SING A C OPY C ONSTRUCTOR ( CONTD.) Object initialization can occur in three ways When an object is used to initialize another in a declaration statement MyClass y; MyClass x = y; When an object is passed as a parameter to a function func1(y); // calls “void func1( MyClass obj )” When a temporary object is created for use as a return value by a function y = func2(); // gets the object returned from “MyClass func2()” See the examples from the book and the supplied codes to have a better understanding of the activities and usefulness of copy constructors. Example: copy-cons.cpp 8 Department of CSE, BUET

U SING D EFAULT A RGUMENTS It is related to function overloading. Essentially a shorthand form of function overloading It allows to give a parameter a default value when no corresponding argument is specified when the function is called. void f1(int a = 0, int b = 0) { … } It can now be called in three different ways. f1(); // inside f1() ‘a’ is ‘0’ and b is ‘0’ f1(10); // inside f1() ‘a’ is ‘10’ and b is ‘0’ f1(10, 99); // inside f1() ‘a’ is ‘10’ and b is ‘99’ We can see that we cannot give ‘b’ a new (non-default) value without specifying a new value for ‘a’. So while specifying non-default values, we have to start from the leftmost parameter and move to the right one by one. 9 Department of CSE, BUET

U SING D EFAULT A RGUMENTS ( CONTD.) Default arguments must be specified only once: either in the function’s prototype or in its definition. All default parameters must be to the right of any parameters that don’t have defaults. void f2(int a, int b = 0); // no problem void f3(int a, int b = 0, int c = 5); // no problem void f4(int a = 1, int b); // compiler error So, once you begin to define default parameters, you cannot specify any parameters that have no defaults. Default arguments must be constants or global variables. They cannot be local variables or other parameters. 10 Department of CSE, BUET

U SING D EFAULT A RGUMENTS ( CONTD.) Relation between default arguments and function overloading. void f1( int a = 0, int b = 0 ) { … } It acts as the same way as the following overloaded functions – void f2( ) { int a = 0, b = 0; … } void f2( int a ) { int b = 0; … } void f2( int a, int b ) { … } Constructor functions can also have default arguments. 11 Department of CSE, BUET

U SING D EFAULT A RGUMENTS ( CONTD.) It is possible to create copy constructors that take additional arguments, as long as the additional arguments have default values. MyClass( const MyClass &obj, int x = 0 ) { … } This flexibility allows us to create copy constructors that have other uses. See the examples from the book to learn more about the uses of default arguments. 12 Department of CSE, BUET

O VERLOADING AND A MBIGUITY Due to automatic type conversion rules. Example 1: void f1( float f ) { … } void f1( double d ) { … } float x = 10.09; double y = 10.09; f1(x); // unambiguous – use f1(float) f1(y); // unambiguous – use f1(double) f1(10); // ambiguous, compiler error Because integer ‘10’ can be promoted to both “float” and “double”. 13 Department of CSE, BUET

O VERLOADING AND A MBIGUITY ( CONTD.) Due to the use of reference parameters. Example 2: void f2( int a, int b ) { … } void f2(int a, int &b ) { … } int x = 1, y = 2; f2(x, y); // ambiguous, compiler error 14 Department of CSE, BUET

O VERLOADING AND A MBIGUITY ( CONTD.) Due to the use of default arguments. Example 3: void f3( int a ) { … } void f3(int a, int b = 0 ) { … } f3(10, 20); // unambiguous – calls f3(int, int) f3(10); // ambiguous, compiler error 15 Department of CSE, BUET

F INDING THE ADDRESS OF AN OVERLOADED FUNCTION Example: void space( int a ) { … } void space( int a, char c ) { … } void (*fp1)(int); void (*fp2)(int, char); fp1 = space; // gets address of space(int) fp2 = space; // gets address of space(int, char) So, it is the declaration of the pointer that determines which function’s address is assigned. 16 Department of CSE, BUET

L ECTURE C ONTENTS Teach Yourself C++ Chapter 5 (Full, with exercises) Except “The overload Anachronism” 17 Department of CSE, BUET