C++ Functions
C++ Functions
CS 201
● Functions
○ Facilitate the design, implementation, operation, and maintenance of large programs
2
Global functions
● Do not belong to a particular class
3
Functions
signature
signature
prototype 4
Example:
Write a global function which takes two int parameters and returns their largest
#include <iostream>
using namespace std;
int main() {
int larger = findMax( 42, 16 );
cout << "The larger of 42 and 16 is " << larger << endl;
return 0;
}
int main() {
int a = 10;
cout << a << " squared: "
<< square( a ) << endl;
return 0;
}
int main() {
int a = 10;
cout << a << " squared: "
<< square( a ) << endl;
return 0;
}
int main() {
int a = 10;
cout << a << " squared: "
<< square( a ) << endl;
return 0;
}
● Pass-by-value
○ Copy of the argument’s value is passed to the called function
○ Changes to the copy do not affect the original argument’s value in the caller
■ Prevents accidental side effects of functions
○ Default parameter passing
● Pass-by-reference
○ Gives called function the ability to access and modify the caller’s argument data directly
11
Pass-by-reference
● Reference variable int count;
○ An alias, which is another name for an already existing variable int& no = count;
○ & is placed after the variable type count = 4;
○ A reference should be initialized with a variable. Then, this variable cout << no << endl;
may be referenced by either the variable name or the reference
name
● Advantages of pass-by-reference
○ When used for objects, it is good for performance reasons, because it eliminates the
pass-by-value overhead of copying large amounts of data
○ A useful way to be able to return more than one value
● Disadvantages of pass-by-reference
○ Pass-by-reference can weaken security since the called function can corrupt the caller’s data
○ Hard to tell from the function call if it is pass-by-reference (so cannot tell if it will be modified)
○ Cannot pass a literal value (or an expression or a variable of a different but compatible type) to
a reference type parameter (e.g., nextIntByRef( 4 ) is an invalid call)
16
Principle of least privilege
● Functions should not be given the capability to modify its parameters unless
it is absolutely necessary
17
Principle of least privilege
#include <iostream> void foo( const Book& B ){
using namespace std; // B is a constant reference, thus it CANNOT change
class Book{ // a data member or call a non-const member function
public:
void setNo( int i ); // THREE STATEMENTS BELOW LEAD TO COMPILE-TIME ERRORS
int getNo( ) const; // B.publicNo = 10;
void displayNo( ); // B.setNo(20);
int publicNo; // B.displayNo();
private: cout << B.getNo() << endl;
int no; }
}; int main() {
void Book::setNo( int n ){ Book A;
no = n; foo( A );
} return 0;
int Book::getNo( ) const{ }
return no;
} For passing large objects, use a constant reference parameter
void Book::displayNo( ){ to simulate the appearance and security of pass-by-value and
cout << no << endl;
avoid the overhead of passing a copy of the large object. 18
}
Exercise (returning more than one value):
Write a global function which takes two int parameters and computes and returns the sum of the
inputs and the product of the inputs. The input parameters should not be modified. Use the principle
of least privilege.
return 0;
} 19
Exercise (returning more than one value):
Write a global function which takes two int parameters and computes and returns the sum of the
inputs and the product of the inputs. The input parameters should not be modified. Use the principle
of least privilege.
void computeSumProduct( const int x, const int y, int& sum, int& product ){
sum = x + y;
product = x * y;
}
int main(){
int s, p, c = 10;
double r, t = 3.2;
computeSumProduct( c, t, s, p );
return 0;
}
20
Storage class, scope, and linkage
● Each identifier has several attributes
○ Name, type, size, and value
○ Also storage class, scope, and linkage
■ Identifier’s storage class determines the period during which that identifier exists in
memory (automatic and static variables)
■ Identifier’s linkage determines whether an identifier is known only in the source file
where it is declared or across multiple files that are compiled, then linked together (use
of the extern specifier)
21
Storage class (automatic variables)
What is the output?
● Only a local variable and a function void foo() {
parameter can be of the automatic storage int k = 10;
cout << k << endl;
class k++;
if ( k > 5 ) {
○ Created when the program execution enters the
int a = 50;
block in which it is defined
cout << a << endl;
○ Exists while the block is active k++;
}
○ Destroyed when the execution exits the block
cout << k << endl;
}
● Default declaration (can also be declared int main() {
int k = 20;
with keyword auto) cout << k << endl;
k++;
foo();
cout << k << endl;
Automatic variables are stored in the call stack return 0;
} 22
Storage class (static local variables)
What is the output?
● A local variable declared with static void g1() {
int a = 4;
○ Exists from the point at which the program begins
cout << a << endl;
execution
a++;
○ Initialized only once when its declaration is first }
encountered void g2() {
static int b = 4;
○ Retains its value when the function (in which this cout << b << endl;
local variable is declared) returns to its caller b++;
■ Next time this function is called, it contains }
the value it had at the end of this function’s int main() {
last call g1();
g1();
■ However, known only in this function (that is,
g2();
its scope is only this function) g2();
// cout << a; compile-time error
// cout << b; compile-time error
Static local variables are stored in the data section return 0;
} 23
Storage class (static global variables)
What is the output?
● A global variable is static by its definition int k = 4;
void h1() {
(keyword static is not used) cout << k << endl;
○ Defined by placing variable declaration outside any k = 7;
}
class or function definition
void h2() {
○ Created at the beginning of the program cout << k << endl;
k++;
○ Retains its value throughout the program execution }
○ Can be referenced by any function that follows its void h3() {
int k = 1;
declaration cout << k << endl;
Do not use them as an alternative to parameter passing k = 20;
}
(do not use them if it is not that necessary!!!)
int main() {
cout << k << endl;
h1(); cout << k << endl;
h2(); cout << k << endl;
h3(); cout << k << endl;
Global variables are also stored in the data section
return 0;
} 24
Scope (file scope)
● Scope of an identifier: a portion of the program where it can be referenced
● Identifiers (global variables, global function definitions/prototypes) declared
outside a function or a class all have the file scope
○ These identifiers can be referenced in all functions from the point at which they are declared
until the end of the file
27
Function templates
● More compact and convenient form of overloading
○ Identical program logic and operations for each data type
28
Write a generic maximum function using a function template
main.cpp #ifndef __MAX_H max.h
#include <iostream>
#include <string> #define __MAX_H
using namespace std;
template < typename T >
#include "max.h" T maximum( T num1, T num2 ) {
if ( num1 > num2 )
int main() { return num1;
cout << "The maximum of 5 and 3: "; else
cout << maximum( 5, 3 ) << endl; return num2;
}
double a = 4.5; #endif
cout << "The maximum of a and 5.6: ";
cout << maximum( a, 5.6 ) << endl; Output
The maximum of 5 and 3:5
string s1 = "Hello", s2 = "World";
The maximum of a and 5.6: 5.6
cout << "The maximum of s1 and s2: ";
The maximum of s1 and s2: World
cout << maximum( s1, s2 ) << endl;
30
31
©1992-2014 by Pearson Education, Inc. All Rights Reserved.
©1992-2014 by Pearson Education, Inc. All Rights Reserved.
32
©1992-2014 by Pearson Education, Inc. All Rights Reserved.
33
Math functions
● The <cmath> header file provides a
collection of functions that enable you to
perform common mathematical calculations
34
©1992-2014 by Pearson Education, Inc. All Rights Reserved.