OBJECT ORIENTED
PROGRAMMING
Content
2
Function prototypes
Function with empty parameter lists
Function, file, and block scope
Function signature
Default arguments
Argument coercion
Demotion and promotion of arguments and return types
Function Overloading
Storage classes
Reference variables
Reference parameters
Passing arguments (pass-by-value, pass-by-reference)
Objectives
3
By the end you should recognize:
Difference and uses of function header, prototype and signature
Declaring functions using prototypes
How to implement and use a function that has no return type and no parameters
How to implement and use a function that has no return type and has parameters
How to implement and use a function that has return type and parameters
Coding functions whose arguments are passed either by-value or by-reference
Using and implementing local, global, automatic and static identifiers
Different scopes function, file and block
Notion of function overloading and how the compiler select proper function from
invocation statements
Function Prototype
Consists of the function's return type, name and parameter list
(
number, types and order of parameters)
Also called function declaration
Usually placed at the top of the program to tell the compiler that the
function exists
Same as corresponding function header except that
Parameter names are optional
Examples
5
int square( int x )
{
return x * x;
}
void useLocal( void )
{
int x = 25;
cout << "\nlocal x is " << x << endl;
x++;
cout << "local x is " << x << endl;
}
Compilation Error
6#include <iostream>
using std::cin;
using std::cout;
using std::endl;
int main()
{
int a = 10;
cout << a << " squared: " << square( a ) << endl;
return 0;
}
int square( int x )
{
return x * x;
}
Error: function undeclared before use
Solution -1
7#include <iostream>
using std::cin;
using std::cout;
using std::endl;
int square( int x )
{
return x * x;
}
int main()
{
int a = 10;
cout << a << " squared: " << square( a ) << endl;
return 0;
}
Solution -2
8#include <iostream>
using std::cin;
using std::cout;
using std::endl;
int square( int ); // prototype for function square
int main()
{
int a = 10;
cout << a << " squared: " << square( a ) << endl; return 0;
}
int square( int x )
{
return x * x;
Empty Parameter Lists
Specified by writing either
void
or nothing at all in parentheses
int
sum();
OR
int
sum(
void
);
Scope
Identifiers
Variable or object
Function
Scope of Identifier
Portion of the program where an identifier can be used
Types of scopes for an identifier
Function scope
File scope
File Scope
For an identifier declared outside any function
Identifier is “known” and can be used in all functions from the point at
which it is declared until the end of the file
Examples
Global variables, function definitions and function prototypes placed
Function Scope
Can be used anywhere in the function in which they appear
Cannot be referenced outside the function body
Examples
Block Scope
Blocks are defined by the beginning left brace ( { ) and the
terminating right brace ( } )
Identifiers declared inside a block have block scope
Block scope begins at the identifier’s declaration
Block scope ends at the terminating right brace (}) of the block in which
14
#include <iostream> using std::cout; using std::endl;
int x = 1; // global variable
int main() {
int x = 5; // local variable to main
cout << "local x in main's outer scope is " << x << endl;
{ // start new scope
int x = 7; // hides x in outer scope cout << "local x in main's inner scope is " << x << endl; } // end new scope
cout << "local x in main's outer scope is " << x << endl;
return 0; }
File Scope (defined outside any class or function)
Function / Outer Block Scope (can be used only inside the outer block defined in Main)
Function Signature
The portion of a function prototype that includes the name of the
function and the types of its arguments
Does not specify the function’s return type
The scope of a function is the region of a program in which the
function is known and accessible
Functions in the same scope must have unique signatures
15int
square(
int
);
Compilation Error -1
16
#include <iostream>
using std::cin;
using std::cout;
using std::endl;
int square( int x )
{
return x * x;
}
void square( int x) {
cout<< x * x; }
int main()
{
return 0;
} // end main
• Two functions in the global(
file
) scope • They have the same signature:square(int)
Compilation Error -2
Arguments (in function call) and parameters (in function header)
must
match in
Number
, Order, and Data Types
17#include <iostream> using namespace std;
int boxVolume( int length, int width, int height ) { return length * width * height; }
int main() {
cout<< boxVolume(); // Error#1: 'boxVolume' : function does not take 0 arguments cout<< boxVolume(10); // Error#2: 'boxVolume' : function does not take 1 argument cout<< boxVolume(10,5); // Error#3: 'boxVolume' : function does not take 2 arguments cout<< boxVolume(10,5,2);
Default Argument
18
#include <iostream> using namespace std;
int boxVolume( int length=1 , int width=1 , int height=1 ) {
return length * width * height; }
int main() {
cout<< boxVolume(); //equivalent to cout<< boxVolume(1,1,1);
cout<< boxVolume(10); //equivalent to cout<< boxVolume(10,1,1);
cout<< boxVolume(10,5); //equivalent to cout<< boxVolume(10,5,1);
cout<< boxVolume(10,5,2); //equivalent to cout<< boxVolume(10,5,2);
return 0; }
Default Argument (cont.)
C++ feature allows a function to be called with fewer arguments
than the function’s parameters
A default value to be passed to a parameter
Used when the function call does not specify an argument for that
parameter
Must be the rightmost argument(s) in a function’s parameter list
Should be specified with the first occurrence of the function name
Compilation Error -1
20
#include <iostream> using namespace std;
int boxVolume( int length=1 , int width=1 , int height=1 ) ;
int main() {
cout<< boxVolume(); cout<< boxVolume(10); cout<< boxVolume(10,5); cout<< boxVolume(10,5,2); return 0;
}
int boxVolume( int length=1 , int width=1 , int height=1 ) {
return length * width * height; }
Compilation Error -2
21
#include <iostream> using namespace std;
int boxVolume( int length=1, int width , int height ) ;
int main() {
cout<< boxVolume(10,5,2); return 0;
}
int boxVolume( int length , int width , int height ) { return length * width * height; }
Argument Coercion
Important feature that forcing arguments to the appropriate types
specified by the parameter declarations
Arguments (in function call) and parameters (in function header)
must
match in Number
, Order, and
Data Types
Promotion/Demotion may occur when the type of a function
1- Argument Demotion
23
#include <iostream>
using namespace std;
int boxVolume( int length, int width , int height ) ;
int main() {
cout<< boxVolume(10.5,5.7,2.4); return 0;
}
int boxVolume( int length , int width , int height )
{
return length * width * height;
}
2- Argument Promotion
24
#include <iostream>
using namespace std;
void boxVolume( double length, double width , double height ) ;
int main() {
boxVolume(10,5,2); return 0;
}
void boxVolume(double length , double width , double height )
{
cout<< length * width * height;
}
3- Return Type Demotion
25
#include <iostream>
using namespace std;
double boxVolume( double length, double width , double height ) ;
int main() {
int r = boxVolume(10.5,5.7,2.3); return 0;
}
double boxVolume(double length , double width , double height )
{
return length * width * height;
}
4- Return Type Promotion
26
#include <iostream>
using namespace std;
int boxVolume( int length, int width , int height ) ;
int main() {
double r = boxVolume(10,5,2); return 0;
}
int boxVolume(int length , int width , int height )
{
return length * width * height;
}
Function Overloading
Creating several functions of the same name that perform similar
tasks, but on different data types
Overloaded functions have
Same name
Different signature
Compiler selects proper function to execute based on number,
types and order of arguments in the function call
28
#include <iostream>
using std::cout;
using std::endl;
// function square for int values
int square( int x )
{
cout << "square of integer " << x << " is ";
return x * x;
}
// function square for double values
double square( double y )
{
cout << "square of double " << y << " is ";
return y * y;
}
int main()
{
cout << square( 7 ); // calls int version
cout << endl;
cout << square( 7.5 ); // calls double version
cout << endl;
return 0;
29
#include <iostream>
using std::cout;
using std::endl;
// function multiply for two parameters
int multi( int x, int y )
{
return x * y;
}
// function multiply for one parameter
int multi( int y )
{
return y * 1;
}
int main()
{
cout << multi( 7,5 ); // calls 2 parameter version
cout << endl;
cout << multi( 7 ); // calls 1 parameter version
cout << endl;
return 0;
30
#include <iostream>
using std::cout;
using std::endl;
// function multiply for two parameters
int multi( int x, double y )
{
return x * y;
}
// function multiply for two parameter but with different order
double multi( double y , int x)
{
return y * x;
}
int main()
{
cout << multi( 7,5.5 ); // calls int,double version
cout << endl;
cout << multi( 7.5,3 ); // calls double,int version
cout << endl;
return 0;
Storage Classes
Identifier’s storage class
Determines the period during which that identifier exists in memory
Two main categories
Static , Automatic
Storage Class Specifiers
Keyword
auto
Keyword
static
Variables are of automatic storage class by default
Automatic & Static Variables
Automatic variables
Created when program execution enters block in which they are defined
Exist while the block is active
Destroyed when the program exits the block
ONLY
local variables and parameters can be of automatic storage
Static Variables
Exist from the point at which the program begins execution
Initialized once when their declarations are encountered
Last for the duration of the program
33
#include <iostream>
using std::cout;
using std::endl;
void useLocal( void ); // function prototype
void useStaticLocal( void ); // function prototype
void useGlobal( void ); // function prototype
int x = 1; // global variable
int main()
{ useLocal(); useStaticLocal(); useGlobal(); useLocal(); useStaticLocal(); useGlobal();
return 0;
} // end main
void useLocal( void )
{
int x = 25; // initialized each time useLocal is called
cout << "\nlocal x is " << x << " on entering useLocal" << endl;
x++;
cout << "local x is " << x << " on exiting useLocal" << endl;
34
void useStaticLocal( void )
{
static int x = 50; // initialized first time useStaticLocal is called
cout << "\nlocal static x is " << x << " on entering useStaticLocal"
<< endl;
x++;
cout << "local static x is " << x << " on exiting useStaticLocal"
<< endl;
}
// useGlobal modifies global variable x during each call
void useGlobal( void )
{
cout << "\nglobal x is " << x << " on entering useGlobal" << endl;
x *= 10;
cout << "global x is " << x << " on exiting useGlobal" << endl;
35
local x is 25 on entering useLocal
local x is 26 on exiting useLocal
local static x is 50 on entering useStaticLocal
local static x is 51 on exiting useStaticLocal
global x is 1 on entering useGlobal
global x is 10 on exiting useGlobal
local x is 25 on entering useLocal
local x is 26 on exiting useLocal
local static x is 51 on entering useStaticLocal
local static x is 52 on exiting useStaticLocal
Reference Variables
36
// create an integer
int a ;
// Now create another name for the // same integer
int& b = a ; //OR
Int &b = a ;
grab
memory for
an integer
and labels it
as "a"
"b" is just
another label
for the same
memory
b
is a "reference".
int&
means "make a label to reference an integer"
Reference Variables (cont.)
Can be used as aliases for other variables
An alias is simply another name for the original variable
All operations supposedly performed on the alias (i.e., the
reference) are actually performed on the original variable
Must be initialized in their declarations
Cannot be reassigned afterward
Example
int count = 1;
int &
cRef = count;
38
#include <iostream>
using std::cout;
using std::endl;
int main()
{
int x = 3;
int &y = x; // y refers to (is an alias for) x
cout << "x = " << x << endl << "y = " << y << endl;
y = 7; // actually modifies x
cout << "x = " << x << endl << "y = " << y << endl;
return 0; // indicates successful termination
} // end main
x = 3
y = 3
x = 7
y = 7
#include <iostream>
using std::cout;
using std::endl;
int main()
{
int x = 3;
int &y; // Error: y must be initialized
cout << "x = " << x << endl << "y = " << y << endl;
y = 7;
cout << "x = " << x << endl << "y = " << y << endl;
return 0;
}
Example #1
Passing Arguments
Two ways to pass arguments to functions
Pass-by-value
A copy of the argument’s value is passed to the called function
Changes to the copy do not affect the original variable’s value in the
caller
Prevents accidental side effects of functions
Pass-by-reference
Gives called function the ability to access and modify the caller’s
argument data directly
Reference Parameter
An alias for its corresponding argument in a function call
& placed after the parameter type in the function prototype and
function header
Example
void
squareByReference(
int &
numberRef ) ;
Parameter name in the body of the called function actually refers to
Pass By Value
41
#include <iostream>
using std::cout;
using std::endl;
int squareByValue( int ); // function prototype (value pass)
int main()
{
int x = 2;
// demonstrate squareByValue
cout << "x = " << x << " before squareByValue\n";
cout << "Value returned by squareByValue: "
<< squareByValue( x ) << endl;
cout << "x = " << x << " after squareByValue\n" << endl;
return 0;
}
int squareByValue( int number )
{
return number *= number; // caller's argument not modified
Pass By Reference
42
#include <iostream>
using std::cout;
using std::endl;
int squareByReference( int& ); // function prototype (value pass)
int main()
{
int z = 4;
// demonstrate squareByReference
cout << "z = " << z << " before squareByReference" << endl;
squareByReference( z );
cout << "z = " << z << " after squareByReference" << endl;
return 0;
}
void squareByReference( int &numberRef ) { numberRef *= numberRef; // caller's argument modified
}
4
z
Function Call Stack
Sometimes called the program execution stack
Supports the function call/return mechanism
Each time a function calls another function, a stack frame (also known
as an activation record) is pushed onto the stack
Stack Frame
Maintains the return address that the called function needs to return to
Contains automatic variables—parameters and any local variables the
function declares
Function Call Stack (cont.)
44
Called functions are
pushed at the top of the stack Returning functions are
Example
45
#include <iostream>
using std::cin;
using std::cout;
using std::endl;
int square( int ); // prototype for function square
int main()
{
int a = 10;
cout << a << " squared: " << square( a ) << endl; return 0;
}
int square( int x )
{
return x * x;
46
48
Program control returns to
main
and
Common Compilation Errors
When function is invoked before it is defined and the function does not have a
function prototype
Two functions in the same scope have the same signature
Mismatching function header with function call OR function header with
function prototype in the number, type and order of parameters and arguments
Using multiple storage class specifiers for a variable
Using the same name of identifiers in the same scope
Not initializing a reference variable when it is declared
Specifying default arguments in both function’s prototype and header
Function with default arguments omitted might be called identically to another
overloaded function
Included Sections
50