Download presentation
Presentation is loading. Please wait.
Published byDaisy Walsh Modified over 9 years ago
2
2Object-Oriented Program Development Using C++
3
3 Function Declarations and Definitions Analogize functions to methods –Share same basic features –Unlike methods, do not act on implied object Purpose: perform set of tasks Options –May accept input in form of arguments –May return a value Function activated by a call (invocation) statement
4
4Object-Oriented Program Development Using C++ Figure 7-1 A Function as a Machine
5
5Object-Oriented Program Development Using C++ Figure 7-2 Calling and Passing Data to a Function
6
6Object-Oriented Program Development Using C++ Function Prototypes Prototype: declaration statement identical to method's Purpose: –Specifies arguments (if any) caller is to provide –Alerts caller to return value Syntax template: –returnDataType functionName (list of argument data types); Keyword "void" in returnType if no value returned Example: int findMax (int, int);
7
7Object-Oriented Program Development Using C++ Calling a Function Function calls like method calls Requirements –Function name –Arguments (if any) specified by prototype Call by value: function receives copies of values Example: int max = findMax (firstnum, secnum);
8
8Object-Oriented Program Development Using C++ Figure 7-3 findMax() Receives Actual Values
9
9Object-Oriented Program Development Using C++ Defining a Function C++ function consists of header and body –Form follows form of class method Header –Return type, name, formal parameters (arguments) Body –Set of statements bounded by braces { } –Local variables and constants may be declared –If value returning, return statement required
10
10Object-Oriented Program Development Using C++ Figure 7-4 General Format of a Function
11
11Object-Oriented Program Development Using C++ Figure 7-5 Storing Values into Parameters
12
12Object-Oriented Program Development Using C++ Figure 7-6 Structure of a Function Body
13
13Object-Oriented Program Development Using C++ Placement of Statements Declare or define before use: –All preprocessor commands, variables, named constants, and function calls –Place in upper left section of file (or function) Place limited use variables next to statements Program logic occupies central portion of function Return statement (if needed) is last line Comments may be inserted where needed
14
14Object-Oriented Program Development Using C++ Variations Function can be analogized to a closed box Six major variations of the function "box" Function stubs –Placeholder for final unit (under construction) –Minimum requirement: compile and link with caller Functions with empty parameter lists –Common type: display function –Parentheses either empty or include "void" keyword
15
15Object-Oriented Program Development Using C++ Variations (continued) Default arguments –Extend parameter list of existing functions –Example: int findMax (int x = 10, int y = 15); –Four rules must be followed in implementation Reusing function names –Overloading: common names, different parameters –Compiler distinguishes by parameter list
16
16Object-Oriented Program Development Using C++ Variations (continued) Inline functions –Include definition with declaration –Use keyword "inline" before return data type –Saves overhead of function call Function Templates –Model for a family of functions –Variation around data types –Use template prefix: template –T is generic data type
17
17Object-Oriented Program Development Using C++ Variable Scope Scope –Variable visibility –Three categories: global, local, and class Global variable declared outside int main ( ) Local variable declared within function body Class scope: instance variables and member methods Scope should not be confused with data type
18
18Object-Oriented Program Development Using C++ Figure 7-7 A Function Can Be Considered a Closed Box
19
19Object-Oriented Program Development Using C++ Figure 7-8 The Three Storage Areas Created by Program 7-7
20
20Object-Oriented Program Development Using C++ Figure 7-9 Relating the Scope and Type of a Variable
21
21Object-Oriented Program Development Using C++ Scope Resolution Operator Default resolution of name conflict –Local variable takes precedence over global –Innermost nested variable trumps outer Scope resolution operator ( : : ) –Overrides default resolution –Prefix operator to variable –Example: cout << ::number << endl;
22
22Object-Oriented Program Development Using C++ Misuse of Globals Global variables often adversely impact programs –Reduce modularity: functions not independent units –Reduce readability: input to function obscured –Make maintenance difficult: errors hard to trace Use global variables in special circumstances –Criterion: most (if not all) functions depend on global
23
23Object-Oriented Program Development Using C++ Class Scope Class scope: applies to instance variables and member functions Globals hidden by class variable with same name Local variables trump global and class variables with same name Function interface represents three scope categories
24
24Object-Oriented Program Development Using C++ Figure 7-10 Example of Class Scope
25
25Object-Oriented Program Development Using C++ Variable Storage Categories Duration refers to variable's lifetime –Variables must be allocated storage before use –All variables deallocated storage when program halts –Interim period: allocation determined by storage class Four storage classes –auto, static, extern, register –Qualify variable by placing keyword before name Scope vs. duration –Scope is spatial while duration is temporal
26
26Object-Oriented Program Development Using C++ Local Variable Storage Categories auto (automatic) –Default setting –Duration limited to time of function execution static –Initialized at compile-time by constant expression –Duration for lifetime of program –Retains value between function calls register –Located in faster memory near ALU –Otherwise similar to automatic variables
27
27Object-Oriented Program Development Using C++ Global Variable Storage Categories Nonclass global variables –extern Extends scope beyond normal boundaries extern declaration statement needed –static: prevents extension outside file Global class variables –Static member data and methods shared by all objects –Keyword "static" used only in declaration
28
28Object-Oriented Program Development Using C++ Figure 7-12 Extending the Scope of a Global Variable
29
29Object-Oriented Program Development Using C++ Figure 7-13 Sharing the Static Class Variable taxRate
30
30Object-Oriented Program Development Using C++ Pass by Reference Using Reference Parameters Pass by reference: include address in parameter list Syntax template and note: –dataType& referenceName –Ampersand means "address of" Example header and call –void newval(double& xnum, double& ynum) –newval(firstnum, secnum); Formal parameters reference memory location of actual arguments
31
31Object-Oriented Program Development Using C++ Figure 7-15 The Equivalence of Actual and Formal Arguments in Program 7-13
32
32Object-Oriented Program Development Using C++ Figure 7-16 Relationship Between Arguments and Parameters
33
33Object-Oriented Program Development Using C++ Recursion Recursion: self-reference Two types of recursive functions –Direct: function invokes itself without intermediary –Indirect (mutual): invocation through called function
34
34Object-Oriented Program Development Using C++ Mathematical Recursion Mathematical recursion –Divide and conquer –Large problem broken down into smaller versions Function self-calls until base case reached Base case causes recursion to unwind Example: compute factorial –Recursive case: return product of number x factorial ( ) –Base case: return value of 1 when number reduced to 0
35
35Object-Oriented Program Development Using C++ How the Computation is Performed Function call memory requirements met by stack –Arguments, local variables, return value –Pointer to next instruction Growing stack represents suspended functions Implications of reaching base case –Value of 1 placed on stack –Recursive calls (and stack growth) halted –Suspended functions resume execution in reverse order
36
36Object-Oriented Program Development Using C++ Figure 7-18 The Stack for the First Call to factorial()
37
37Object-Oriented Program Development Using C++ Figure 7-19 The Stack for the Second Call to factorial()
38
38Object-Oriented Program Development Using C++ Figure 7-20 The Stack for the Third Call to factorial()
39
39Object-Oriented Program Development Using C++ Recursion versus Iteration Recursive functions have iterative counterparts Criteria for selecting style –Amount of code required to implement algorithm –Technique enabling best visualization of problem Bias toward iteration –Generally incurs less overhead (memory requirements) –Many programmers better comprehend technique
40
40Object-Oriented Program Development Using C++ Exception Handling Traditional method –Use return statement of int main ( ) –Integer values represent error types A systematic approach: exception handling –Exception object created at point of error by method –Exception passed (thrown) to exception handler –Handler "catches" and corrects problem Syntactic elements: try, throw, and catch
41
41Object-Oriented Program Development Using C++ Table 7-1 Exception Handling Terminology
42
42Object-Oriented Program Development Using C++ Program Design and Development: Creating a Personal Library Programmers may create their own libraries –Encapsulate desired classes/functions into namespace –Store complete code in one or more files Using personal library file –Include in another file with preprocessor directive –File name and namespace identifier need not coincide –Example: #include using namespace finDates;
43
43Object-Oriented Program Development Using C++ Summary Functions (and methods) are like machines Functions perform set of tasks Functions may take input and may return a value Functions, unlike methods, are not bound to classes Three syntactic structures: prototype, call, definition
44
44Object-Oriented Program Development Using C++ Summary (continued) Six variations: overloading, stubs, empty parameter lists, default arguments, inlining, templates Scope refers to variable visibility Three scope categories: local, global, class Local variables hide globals with same name Class data and method members used by all objects
45
45Object-Oriented Program Development Using C++ Summary (continued) Pass by reference: address passed to function Recursive functions call themselves Recursive algorithms: recursive and base cases Exception handling: system for managing errors Personal library files encapsulated in namespace
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.