CMSC 202 Lesson 6 Functions II. Warmup Correctly implement a swap function such that the following code will work: int a = 7; int b = 8; Swap(a, b); cout.

Slides:



Advertisements
Similar presentations
Pass by Value. COMP104 Pass by Value / Slide 2 Passing Parameters by Value * A function returns a single result (assuming the function is not a void function)
Advertisements

Chapter 6 Advanced Function Features Pass by Value Pass by Reference Const parameters Overloaded functions.
Templated Functions. Overloading vs Templating  Overloaded functions allow multiple functions with the same name.
C++ Programming: Program Design Including Data Structures, Third Edition Chapter 7: User-Defined Functions II.
Lecture 3 Feb 4 summary of last week’s topics and review questions (handout) Today’s goals: Chapter 1 overview (sections 1.4 to 1.6) c++ classes constructors,
Functions CS 308 – Data Structures. Function Definition Define function header and function body Value-returning functions return-data-type function-name(parameter.
1 11/05/07CS150 Introduction to Computer Science 1 Functions Chapter 6, page 303.
1 Chapter 7 Functions Dale/Weems/Headington. 2 Functions l Control structures l every C++ program must have a function called main l program execution.
Review on pointers and dynamic objects. Memory Management  Static Memory Allocation  Memory is allocated at compiling time  Dynamic Memory  Memory.
File Review Declare the File Stream Object Name –ofstream for output to file –ifstream for input from file Associate a File Name with the File Stream Object.
 2003 Prentice Hall, Inc. All rights reserved. 1 Functions Modules: functions and classes Programs use new and “prepackaged” modules –New: programmer-defined.
Function Part II: Some ‘advanced’ concepts on functions.
C++ Functions CS242 COMPUTER PROGRAMMING T.Banan Al-Hadlaq.
Lesson 6 Functions Also called Methods CS 1 Lesson 6 -- John Cole1.
Computer Science 1620 Reference Parameters. Parameters – Pass by Value recall that the parameter of a function is assigned the value of its corresponding.
1 Functions Modules: functions and classes Programs use new and “prepackaged” modules –New: programmer-defined functions, classes –Prepackaged: from the.
CMSC 202 Lesson 12 Operator Overloading II. Warmup  Overload the + operator to add a Passenger to a Car: class Car { public: // some methods private:
1 Chapter 8 Scope, Lifetime, and More on Functions Dale/Weems/Headington.
C++ function call by value The call by value method of passing arguments to a function copies the actual value of an argument into the formal parameter.
Copyright  Hannu Laine C++-programming Part 1 Hannu Laine.
C++ Functions. Objectives 1. Be able to implement C++ functions 2. Be able to share data among functions 2.
Functions Modules in C++ are called functions and classes Functions are block of code separated from main() which do a certain task every C++ program must.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 7 Clicker Questions September 22, 2009.
User Defined Functions Chapter 7 2 Chapter Topics Void Functions Without Parameters Void Functions With Parameters Reference Parameters Value and Reference.
COMPUTER PROGRAMMING. Functions’ review What is a function? A function is a group of statements that is executed when it is called from some point of.
CSIS 113A Lecture 8 Parameters.  Two methods of passing arguments as parameters  Call-by-value  ‘copy’ of value is passed  Call-by-reference  ‘address.
Structure Programming Lecture 8 Chapter 5&6 - Function – part I 12 December 2015.
Functions Sujana Jyothi C++ Workshop Day 2. Functions 3 Parameter transmission modes pass by value (default) pass by reference (&) pass by const reference.
Chapter Functions 6. Modular Programming 6.1 Modular Programming Modular programming: breaking a program up into smaller, manageable functions or modules.
CS1201: PROGRAMMING LANGUAGE 2 FUNCTIONS. OVERVIEW What is a Function? Function Prototype Vs Decleration Highlight Some Errors in Function Code Parameters.
C++ Programming Lecture 13 Functions – Part V The Hashemite University Computer Engineering Department (Adapted from the textbook slides)
1 Chapter 12 Arrays. 2 C++ Data Types structured array struct union class address pointer reference simple integral enum char short int long bool floating.
Object-Oriented Programming in C++ Lecture 4 Constants References Operator overloading.
Lecture 2 Functions. Functions in C++ long factorial(int n) The return type is long. That means the function will return a long integer to the calling.
Constructors Initializing New Objects #include “fraction.h” int main() { float x; float y = 6.7; float z(7.2); Fraction.
1 Reference Variables Chapter 8 Page Reference Variables Safer version of C/C++ pointer. "Refers to" a variable. Like a pointer. Effectively.
Cop3530sp12. Parameter passing call by value- appropriate for small objects that should not be altered by the function call by constant reference- appropriate.
Reference Parameters There are two ways to pass arguments to functions: pass- by-value and pass-by-reference. pass-by-value –A copy of the arguments’svalue.
CMSC 202 Lesson 5 Functions I. Warmup Use setw() to print the following (in tabular format) Fred Flintstone Barney Rubble Bugs Bunny Daffy Duck.
C++ Templates 1. Why Use Templates? C++ requires variables, functions, classes etc with specific data types. However, many algorithms (quicksort for example)
Functions in C++ Top Down Design with Functions. Top-down Design Big picture first broken down into smaller pieces.
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X 1 Chapter 7 Pointers and C-Strings.
Lecture 9 – Array (Part 2) FTMK, UTeM – Sem /2014.
Functions CMSC 202. Topics Covered Function review More on variable scope Call-by-reference parameters Call-by-value parameters Function overloading Default.
FUNCTIONS (C) KHAERONI, M.SI. OBJECTIVE After this topic, students will be able to understand basic concept of user defined function in C++ to declare.
C++ Programming Lecture 13 Functions – Part V By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department.
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.
C++ Templates.
Pointers and Pointer-Based Strings
C Basics.
Chapter 6: Functions Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley.
Global & Local Identifiers
CMSC 202 Lesson 21 Exceptions II.
group work #hifiTeam
Extra.
User Defined Functions
Pointers & Functions.
CMSC 202 Lesson 22 Templates I.
More ‘concepts’ on Function
Pointers and References
Pointers and Pointer-Based Strings
Function Defaults C++ permits functions to be declared with default values for some, or all, of its parameters Allows for the function to be called without.
Templates I CMSC 202.
Functions Imran Rashid CTO at ManiWeber Technologies.
Pointers & Functions.
CMSC 202 Lesson 6 Functions II.
Class rational part2.
Templates CMSC 202, Version 4/02.
More ‘concepts’ on Function
CMSC 202 Lesson 5 Functions I.
Presentation transcript:

CMSC 202 Lesson 6 Functions II

Warmup Correctly implement a swap function such that the following code will work: int a = 7; int b = 8; Swap(a, b); cout << a << “ “ << b << endl;// 8 7

Review Pass by value: Changes to Parameter do NOT affect Argument Syntax: retType funcName( type variable, …) { } Pass by reference: Changes to Parameter DO affect Argument Syntax: retType funcName( type &variable, …) { }

Parameter Passing Rules Pass class-type objects by reference string, vector, Car, Customer, etc. Pass primitive objects by value int, double, float, bool, etc. & can be any where between type and reference, personal choice type& variable

Constant Parameters Don’t want a function to change class-type objects? Use ‘const’ instead of pass-by-value Declares the parameter as constant No changes are allowed to the parameter Prevents copy of entire object Syntax: retType funcName( const type &variable, … ) { } Example: int findItem( const vector &myVec, int key) { }

Const Parameters Example void AddOne (const int& n) { n++; // compiler error } int main ( ) { int x = 42; AddOne ( x ) }

Const Parameter Rules Bottom Line Primitive/Built-in types (int, double, float, …) Pass by value  Function is NOT changing argument Pass by reference  Function IS changing argument Class/User-defined types (string, vector, Car, …) Pass by const reference  Function is NOT changing argument Pass by reference  Function IS changing argument

Function Return Types Return by value? Yes, you usually do this – makes a copy of the value Return by reference? Yes, does not make a copy of the value DANGER – the value/memory MUST be dynamically allocated (and not go out-of-scope when function ends) Return by const value? No, almost never use this Return by const reference? Yes, return class-type objects this way to prevent copy A reference to the original unchangeable object is returned

Default Parameters Allow us to define functions with optional parameters Optional parameter gets a default value Must be right-most parameters, why? Syntax: retType funcName( type variable = defValue ) Example Function that adds between 2 and 5 integers int Add(int a, int b, int c = 0, int d = 0, int e = 0) { return a + b + c + d + e; }

Default Parameters Example int Add(int a, int b, int c = 0, int d = 0, int e = 0) { return a + b + c + d + e; } int main() { cout << Add (1, 2) << endl; cout << Add (1, 2, 3) << endl; cout << Add (1, 2, 3, 4) << endl; cout << Add (1, 2, 3, 4, 5) << endl; }

Overloading Functions C limitation Functions are unique based on name C++ extention Functions are unique based on name AND parameter list (type and number) Overloading Declaring two or more functions with same name Must have different parameter lists Return types are NOT used to differentiate functions

Overloading Example int AddTwo( int a, int b) { return a + b; } double AddTwo( double a, double b) { return a + b; } int main() { cout << AddTwo(3, 4) << endl; cout << AddTwo(3.0, 4.0) << endl; cout << AddTwo(3, 4.0) << endl; cout << AddTwo(3.0, 4) << endl; return 0; }

Interesting… What happens with this? float AddTwo( float a, float b) { return a + b; } int main() { cout << AddTwo(3.0, 4.0) << endl; return 0; }

Function Prototypes C++ allows us to define a function above main OR below it… If function is defined below, we must prototype it Declare the function above main, define below Prototype must match function EXACTLY Syntax: retType funcName( parameter_list ); Why? Easier to find main Easier to read Semi-colon!!!

Prototype Example int AddTwo( int a, int b); double AddTwo( double a, double b); int main() { cout << AddTwo(3, 4) << endl; cout << AddTwo(3.0, 4.0) << endl; return 0; } int AddTwo( int a, int b) { return a + b; } double AddTwo( double a, double b) { return a + b; }

Common Errors… What’s wrong with the following? void swap (int a, int b) { int temp = a; a = b; b = temp; }

Common Errors… bool IsOld (int age, int oldAge) { if (age > oldAge) return true; } Main.cpp: In function `bool IsOld(int, int)': Main.cpp:42: warning: control reaches end of non-void function

Common Errors… int AddOne( int n ); int main ( ) { int x = 42; cout << Addone ( x ) << endl; return 0; } int AddOne (int n) { return n + 1; } Main.cpp: In function `int main()': Main.cpp:6 : `Addone' undeclared (first use this function) Main.cpp:6: (Each undeclared identifier is reported only once for each function it appears in.)

Common Errors… #include using namespace std; int main ( ) { int x = 42; int y = Add ( 66, x); cout << y << endl; return 0; } int Add (int n, int m) { return n + m; } Main.cpp: In function `int main()': Main.cpp :8: `Add' undeclared (first use this function) Main.cpp :8: (Each undeclared identifier is reported only once for each function it appears in.) Main.cpp : In function `int Add(int, int)': Main.cpp :16: `int Add(int, int)' used prior to declaration

Parameter Selection… NO YES NOYES NOYES NO YES Is param a Class-type? Can function change value? Can function change value? Should there Be a default Value? Pass by Reference Const Reference Pass By Value with Default Pass by Value Pass by Reference

Challenge Write a “GetItem” function for a vector that Accepts a vector of strings Accepts an integer i (default of 0) Returns item i in the vector If i is not a valid index for the vector  Returns the first item Write the prototype for the function Hint: for now, assume the vector has at least one item…