Function Overloading and References

Slides:



Advertisements
Similar presentations
Classes & Objects INTRODUCTION : This chapter introduces classes ; explains data hiding, abstraction & encapsulation and shows how a class implements these.
Advertisements

Chapter 7: User-Defined Functions II
Chapter 7 User-Defined Methods. Chapter Objectives  Understand how methods are used in Java programming  Learn about standard (predefined) methods and.
C++ Programming: Program Design Including Data Structures, Third Edition Chapter 7: User-Defined Functions II.
Chapter 7: User-Defined Functions II Instructor: Mohammad Mojaddam.
1 Chapter Three Using Methods. 2 Objectives Learn how to write methods with no arguments and no return value Learn about implementation hiding and how.
Chapter 14: Overloading and Templates
 2006 Pearson Education, Inc. All rights reserved Introduction to Classes and Objects.
Chapter 6: User-Defined Functions I
Chapter 6. 2 Objectives You should be able to describe: Function and Parameter Declarations Returning a Single Value Pass by Reference Variable Scope.
 2006 Pearson Education, Inc. All rights reserved Introduction to Classes and Objects.
About the Presentations The presentations cover the objectives found in the opening of each chapter. All chapter objectives are listed in the beginning.
Lesson 6 Functions Also called Methods CS 1 Lesson 6 -- John Cole1.
Guide To UNIX Using Linux Third Edition
1 Using Classes Object-Oriented Programming Using C++ Second Edition 5.
Using Classes Object-Oriented Programming Using C++ Second Edition 5.
CSM-Java Programming-I Spring,2005 Introduction to Objects and Classes Lesson - 1.
Learners Support Publications Pointers, Virtual Functions and Polymorphism.
C++ for Engineers and Scientists Third Edition
EE4E. C++ Programming Lecture 1 From C to C++. Contents Introduction Introduction Variables Variables Pointers and references Pointers and references.
Chapter 1: A First Program Using C#. Programming Computer program – A set of instructions that tells a computer what to do – Also called software Software.
A First Book of C++: From Here To There, Third Edition2 Objectives You should be able to describe: Function and Parameter Declarations Returning a Single.
Chapter 6: Modularity Using Functions. In this chapter, you will learn about: – Function and parameter declarations – Returning a single value – Returning.
© The McGraw-Hill Companies, 2006 Chapter 4 Implementing methods.
Copyright © 2012 Pearson Education, Inc. Chapter 6: Functions.
Object Oriented Programming with C++/ Session 6 / 1 of 44 Multiple Inheritance and Polymorphism Session 6.
Chapter 6: User-Defined Functions
C++ Programming: From Problem Analysis to Program Design, Fifth Edition, Fifth Edition Chapter 7: User-Defined Functions II.
Learners Support Publications Classes and Objects.
Copyright © 2012 Pearson Education, Inc. Chapter 6: Functions.
An Object-Oriented Approach to Programming Logic and Design Fourth Edition Chapter 6 Using Methods.
Copyright 2004 Scott/Jones Publishing Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 7 Structured Data and Classes.
ADTs and C++ Classes Classes and Members Constructors The header file and the implementation file Classes and Parameters Operator Overloading.
Chapter 10 Introduction to Classes
Data Structures Using C++ 2E1 Inheritance An “is-a” relationship –Example: “every employee is a person” Allows new class creation from existing classes.
Learners Support Publications Functions in C++
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.
CSC241 Object-Oriented Programming (OOP) Lecture No. 6.
Liang, Introduction to C++ Programming, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 6 Advanced Function Features.
C Functions Three major differences between C and Java functions: –Functions are stand-alone entities, not part of objects they can be defined in a file.
Introduction to c++ programming - object oriented programming concepts - Structured Vs OOP. Classes and objects - class definition - Objects - class scope.
A FIRST BOOK OF C++ CHAPTER 6 MODULARITY USING FUNCTIONS.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 15: Overloading and Templates.
Functions Chapter 6. Modular Programming Modular programming: breaking a program up into smaller, manageable functions or modules Function: a collection.
Functions Math library functions Function definition Function invocation Argument passing Scope of an variable Programming 1 DCT 1033.
Programming Fundamentals. Topics to be covered Today Recursion Inline Functions Scope and Storage Class A simple class Constructor Destructor.
Chapter 3: User-Defined Functions I
FUNCTIONS. Midterm questions (1-10) review 1. Every line in a C program should end with a semicolon. 2. In C language lowercase letters are significant.
Array in C++ / review. An array contains multiple objects of identical types stored sequentially in memory. The individual objects in an array, referred.
Functions Skill Area 314 Part B. Lecture Overview Functions Function Prototypes Function Definitions Local Variables Global Variables Default Parameters.
Structure A Data structure is a collection of variable which can be same or different types. You can refer to a structure as a single variable, and to.
Announcements. Practice questions, with and without solutions will be uploaded by Friday 5 th November, make sure to check them before the weekend \\netstorage\Subjects\ITCA-b\Exam.
Mr H Kandjimi 2016/01/03Mr Kandjimi1 Week 3 –Modularity in C++
User-Written Functions
Chapter 7: User-Defined Functions II
Friend Class Friend Class A friend class can access private and protected members of other class in which it is declared as friend. It is sometimes useful.
Introduction to C++ Systems Programming.
FUNCTIONS In C++.
Review: Two Programming Paradigms
Chapter 5 Conclusion CIS 61.
Constructor & Destructor
Programmazione I a.a. 2017/2018.
User-Defined Functions
Chapter 4 void Functions
Object-Oriented Programming Using C++ Second Edition
Classes and Objects.
Submitted By : Veenu Saini Lecturer (IT)
Functions Chapter No. 5.
SPL – PS3 C++ Classes.
Presentation transcript:

Function Overloading and References Session 3 Object Oriented Programming with C++/ Session 3 / 1 of 35

Session Objectives Understand the concept of functions with default arguments Define and use Friend functions advantages disadvantage friend classes Describe function overloading various data types different number of arguments Object Oriented Programming with C++/ Session 3/ 2 of 35

Session Objectives (Contd.) describe the scope for function overloading Explain the use of reference arguments passing references to functions returning references from functions Define and use Inline functions Object Oriented Programming with C++/ Session 3/ 3 of 35

Functions A function declaration gives: the name of the function the type of the value returned (if any) by the function the number and types of the arguments that must be supplied in a call of the function A function declaration may or may not contain argument names. Possible to call a function without specifying all its arguments. Object Oriented Programming with C++/ Session 3/ 4 of 35

Functions with default arguments The function declaration must provide default values for those arguments that are not specified. Whenever a call is made to a function without specifying an argument, the program will automatically assign values to the parameters from the default declaration. void func(int = 1, int = 3, char = '*'); //prototype declaration or void func(int num1,int num2 = 3,char ch = '*'); Object Oriented Programming with C++/ Session 3/ 5 of 35

Default values for arguments Once an argument is given a default value in the list of formal arguments, all of the remaining must have default values also. Only the trailing values can be defaulted. void func(int num1=2,int num2, char ch='+'); //error Default values must be of the correct types or the compiler will issue an error. Default values can be given in either the prototype or the function definition header, but not in both. Highly recommended that the default values be given in the prototype declaration rather than in the function definition. Object Oriented Programming with C++/ Session 3/ 6 of 35

Default values for arguments (cont.) The following calls to the function func declared above func(2,13,'+'); func(1); //default values for second and third arguments func(2,25); //default value for third argument func(); //default values for all three args func(2,,'+'); //invalid If you leave out any arguments in the middle the compiler would not know what you are referring to and will indicate an error. Object Oriented Programming with C++/ Session 3/ 7 of 35

Advantages Default arguments are useful if you want to use arguments, which will almost always have the same value in a function. Also useful when, after a program is written, the programmer decides to increase the capability of a function by adding an argument. Existing function calls can continue to use the old number of arguments, while new function calls can use more. Object Oriented Programming with C++/ Session 3/ 8 of 35

Friend Functions Private data values cannot be read or written to by non-member functions. We need a means to allow a function access to the private part of a class without requiring membership. A non-member function that is allowed access to the private part of a class is called a friend of the class. Object Oriented Programming with C++/ Session 3/ 9 of 35

Friend Functions (Contd.) Class Friend Function Private! Keep out! Except members and friends Object Oriented Programming with C++/ Session 3/ 10 of 35

Friend Functions (Contd.) A function is made a friend of a class by a friend declaration in that class class person{ public: void getdata(); friend void display(person abc); }; void display(person abc) //friend function //without :: operator {//… some code…} The keyword friend is not repeated in the function definition. Object Oriented Programming with C++/ Session 3/ 11 of 35

Friend Functions (Contd.) If the same function needed to access objects from different classes it would be most useful to make it a friend of the different classes class Teacher; //forward declaration class Student{ private: int st_data; public: void getstuddata(); friend void display(Student abc, Teacher xyz); }; Object Oriented Programming with C++/ Session 3/ 12 of 35

Friend Functions (Contd.) class Teacher{ private: int th_data; public: void getteachdata(); friend void display(Student abc, Teacher xyz); }; void display(Student abc, Teacher xyz) {//… some code…} Forward declaration: A class cannot be referred to until it has been declared. Therefore, class Teacher has been declared before the class Student. Object Oriented Programming with C++/ Session 3/ 13 of 35

Features of a friend function Nothing special about a friend function apart from its right to access the private part of a class. Friend function does not have a this pointer. Friend declaration can be placed in either the private or public part of a class specifier. Definition of a friend function does not require the class name with the scope resolution operator prefixed to it. Object Oriented Programming with C++/ Session 3/ 14 of 35

Controversy about friend functions. Friend functions increase flexibility in programming but they are against the principles of object-oriented programming. Breach of integrity in the coding can be controlled to some extent. A friend function has to be declared in the class whose data it will access. This cannot be done if the source code is not available to a programmer. If the source code is available, then existing classes should not be modified as far as possible. Object Oriented Programming with C++/ Session 3/ 15 of 35

Advantages Friend functions provide a degree of freedom in the interface design options. Member functions and friend functions are equally privileged. Major difference is that a friend function is called like func(xobject), while a member function is called like xobject.func(). Designer can select the syntax that is considered most readable. Object Oriented Programming with C++/ Session 3/ 16 of 35

Friend classes Declare a single member function, a few member functions or a whole class as a friend of another class. Example of single function as friend class beta; //forward declaration class alpha{ private: int a_data; public: alpha(){a.data = 10;} void display(beta); }; Object Oriented Programming with C++/ Session 3/ 17 of 35

Friend classes example(Contd.) class beta{ private: int b_data; public: beta(){b_data = 20;} friend void alpha::display(beta bb); }; void alpha::display(beta bb) { cout<<"\n data of beta ="<<bb.b_data; cout<<"\n data of alpha ="<<a_data; } void main(){ alpha a1; beta b1; a1.display(b1); } Object Oriented Programming with C++/ Session 3/ 18 of 35

Friend classes (Contd.) When all or most of the functions of a particular class have to gain access to your class, you can consider allowing the whole class friend privileges. class beta; class alpha{ private: int data; public: friend class beta;//beta is a friend class }; Object Oriented Programming with C++/ Session 3/ 19 of 35

Friend classes (Contd.) class beta{ public: void display(alpha d) //can access alpha {cout<<d.data;} void get_data(alpha d) //can access alpha {int x = d.data;} }; All the member functions of class beta can access the private data members of alpha. However, the public member functions of the class alpha cannot access the private members of the class beta. Object Oriented Programming with C++/ Session 3/ 20 of 35

Function Overloading Used to define a set of functions that are given the same name and perform basically the same operations, but use different argument lists. Polymorphism is essentially one thing having many forms. Therefore functional polymorphism means one function having several forms. void display(); // Display functions void display(const char*); void display(int one, int two); void display(float number); Object Oriented Programming with C++/ Session 3/ 21 of 35

Function Overloading (Contd.) Compiler uses the context to determine which definition of an overloaded function is to be invoked: depends on the number and type of arguments supplied in the call. Only those functions that basically do the same task, on different sets of data, should be overloaded. Object Oriented Programming with C++/ Session 3/ 22 of 35

Advantages Eliminates the use of different function names for the same operation Helps to understand and debug code easily Maintaining code is easier Object Oriented Programming with C++/ Session 3/ 23 of 35

Overloading with various data types Compiler can distinguish between overloaded functions with the same number of arguments, provided their type is different. int square(int); float square(float); double square(double); Can use as many overloadings as desired provided all of the parameter patterns are unique. Many programming languages have overloaded output functions so that you can output any data with the same function name. Object Oriented Programming with C++/ Session 3/ 24 of 35

Overloading with different number of arguments int square(int); //function declarations int square(int,int,int); int asq = square(a) //function calls int bsq = square(x,y,z) Invoke the function that is the best match on the arguments or else the compiler gives an error if no function produces the best match. Note that the way the compiler resolves the overloading is independent of the order in which the functions are declared. Return types of the functions are not considered. Object Oriented Programming with C++/ Session 3/ 25 of 35

Function overloading: Scope rules Overloading mechanism is acceptable only within the same scope of the function declaration class first{ public: void display(); }; class second{ Object Oriented Programming with C++/ Session 3/ 26 of 35

Scope rules (Contd.) void main() { first object1; second object2; object1.display(); //no function overloading takes place object2.display(); } The scope is strictly confined to the classes in which they are declared. Object Oriented Programming with C++/ Session 3/ 27 of 35

Passing arguments by value Called function creates a new variable of the same type as the argument and copies the argument's value into it. Function does not have access to the original variable in the calling program, only to the copy it created. Changes are made to the copy does not affect the original variable. Useful when the function does not have to modify the original variable in the calling program. Object Oriented Programming with C++/ Session 3/ 28 of 35

Passing arguments by value (Contd.) Instead of a value being passed to the function, a reference to the original variable in the calling program is passed Main advantage: Function can access the actual variable in the calling program. Also provides a mechanism for returning more than one value from the function back to the calling program. Object Oriented Programming with C++/ Session 3/ 29 of 35

Passing references to functions A reference provides an alias or an alternate name for an object.     void swap(int& i, int& j)     {       int tmp = i;       i = j;       j = tmp;     }     main()     {       int x, y;       swap(x,y);     } The ampersand (&) tells the compiler to treat the variable as a reference to the actual variable passed from the calling function Object Oriented Programming with C++/ Session 3/ 30 of 35

Passing references (Contd.) Do not think of a reference as a pointer to an object. A reference is the object. It is not a pointer to the object, nor a copy of the object. It is the object. Passing a large structure can be done very efficiently if it is passed by reference. This is a form of information hiding. Object Oriented Programming with C++/ Session 3/ 31 of 35

Functions: Returning references Returning a reference does not return back a copy of the variable, instead an alias is returned. Useful for returning objects. int &fn(int &num) {return(num);} void main() { int n1, n2; n1 = fn(n2); } Function header contains an ampersand before the function name to make the function return a reference variable. Object Oriented Programming with C++/ Session 3/ 32 of 35

Inline Functions When a compiler sees a function call, it usually jumps to the function. At the end of the function it goes back to the instruction following the function call. May save memory space but it takes some extra time. To save execution time in short functions use inline functions An inline function is written just like a normal function in the source file but compiles into inline code instead of into a function. inline float converter(float dollars); Object Oriented Programming with C++/ Session 3/ 33 of 35

Inline Functions (Contd.) Functions that are very short, say one or two statements, are suitable for inlining Inline function is shown as a separate entity in source file but when program is compiled, the function body is actually inserted into the program wherever a function call occurs. fn1() fn1(); statements; mfunc(); funcy(); main() Code repeatedly placed in function Code placed inline Object Oriented Programming with C++/ Session 3/ 34 of 35

Inline functions: points to be noted Compiler must see the function definition and not just the declaration before the first function call. The inline keyword is actually just a request to the compiler. Sometimes it ignores the request and compiles the function as a normal function. When you define an inline function for an application that involves different source files, you are not allowed to give different implementations of the inline member function in different source files. Object Oriented Programming with C++/ Session 3/ 35 of 35