2Object-Oriented Program Development Using C++ 3 Function Declarations and Definitions Analogize functions to methods –Share same basic features –Unlike.

Slides:



Advertisements
Similar presentations
Etter/Ingber Engineering Problem Solving with C Fundamental Concepts Chapter 4 Modular Programming with Functions.
Advertisements

C++ Programming: Program Design Including Data Structures, Third Edition Chapter 7: User-Defined Functions II.
Chapter 7: User-Defined Functions II
C++ Programming: Program Design Including Data Structures, Third Edition Chapter 7: User-Defined Functions II.
Chapter 7: User-Defined Functions II Instructor: Mohammad Mojaddam.
 2006 Pearson Education, Inc. All rights reserved Functions.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 5 - Functions Outline 5.1Introduction 5.2Program.
Chapter 6. 2 Objectives You should be able to describe: Function and Parameter Declarations Returning a Single Value Pass by Reference Variable Scope.
Methods of variable creation Global variable –declared very early stage –available at all times from anywhere –created at the start of the program, and.
 2003 Prentice Hall, Inc. All rights reserved. 1 Functions Modules: functions and classes Programs use new and “prepackaged” modules –New: programmer-defined.
1. 2 FUNCTION INLINE FUNCTION DIFFERENCE BETWEEN FUNCTION AND INLINE FUNCTION CONCLUSION 3.
Lesson 6 Functions Also called Methods CS 1 Lesson 6 -- John Cole1.
1 Functions Modules: functions and classes Programs use new and “prepackaged” modules –New: programmer-defined functions, classes –Prepackaged: from the.
Chapter 6: Functions.
IT PUTS THE ++ IN C++ Object Oriented Programming.
Java Methods By J. W. Rider. Java Methods Modularity Declaring methods –Header, signature, prototype Static Void Local variables –this Return Reentrancy.
C++ for Engineers and Scientists Third Edition
1 Chapter 9 Scope, Lifetime, and More on Functions.
Operator Precedence First the contents of all parentheses are evaluated beginning with the innermost set of parenthesis. Second all multiplications, divisions,
chap13 Chapter 13 Programming in the Large.
C Functions Programmer-defined functions – Functions written by the programmer to define specific tasks. Functions are invoked by a function call. The.
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.
C++ for Engineers and Scientists Second Edition Chapter 6 Modularity Using Functions.
Introduction to C++ Systems Programming. Systems Programming: Introduction to C++ 2 Systems Programming: 2 Introduction to C++  Syntax differences between.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. C How To Program - 4th edition Deitels Class 05 University.
1 Chapter 8 Scope, Lifetime, and More on Functions Dale/Weems/Headington.
Copyright © 2012 Pearson Education, Inc. Chapter 6: Functions.
Chapter 6: User-Defined Functions
C++ Programming: From Problem Analysis to Program Design, Fifth Edition, Fifth Edition Chapter 7: User-Defined Functions II.
Chapter 13 Programming in the Large Dr. Jiung-yao Huang Dept. Comm. Eng. Nat. Chung Cheng Univ. TA: 鄭筱親 陳昱豪.
Learners Support Publications Classes and Objects.
Copyright © 2012 Pearson Education, Inc. Chapter 6: Functions.
CPS120: Introduction to Computer Science Functions.
Chapter 10 Introduction to Classes
Liang, Introduction to C++ Programming, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 6 Advanced Function Features.
1 Announcements Note from admins: Edit.cshrc.solaris instead of.tcshrc Note from admins: Do not use delta.ece.
Structure Programming Lecture 8 Chapter 5&6 - Function – part I 12 December 2015.
Starting Out with C++ Early Objects ~~ 7 th Edition by Tony Gaddis, Judy Walters, Godfrey Muganda Modified for CMPS 1044 Midwestern State University 6-1.
#include using namespace std; // Declare a function. void check(int, double, double); int main() { check(1, 2.3, 4.56); check(7, 8.9, 10.11); } void check(int.
2 Objectives You should be able to describe: Object-Based Programming Classes Constructors Examples Common Programming Errors.
A FIRST BOOK OF C++ CHAPTER 6 MODULARITY USING FUNCTIONS.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Brief Edition Chapter 6 Functions.
Functions Math library functions Function definition Function invocation Argument passing Scope of an variable Programming 1 DCT 1033.
1 MORE ON MODULAR DESIGN: MODULE COMMUNICATIONS. 2 WHEN A FUNCTION IS INVOKED, MEMORY IS ALLOCATED LOCALLY FOR THE FORMAL PARAMETERS AND THE VALUE OF.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 6: Functions.
Functions. Predefined Functions C++ comes with libraries of code that can be reused in your programs. The code comes in the form of predefined functions.
 2000 Prentice Hall, Inc. All rights reserved Introduction Divide and conquer –Construct a program from smaller pieces or components –Each piece.
Functions Skill Area 314 Part B. Lecture Overview Functions Function Prototypes Function Definitions Local Variables Global Variables Default Parameters.
Programming Fundamentals1 Chapter 7 INTRODUCTION TO CLASSES.
A First Book of ANSI C Fourth Edition
 2000 Prentice Hall, Inc. All rights reserved Program Components in C++ Function definitions –Only written once –These statements are hidden from.
1 Chapter 8 Scope, Lifetime, and More on Functions CS185/09 - Introduction to Programming Caldwell College.
1 This week Basics of functions Stack frames Stack vs. Heap (brief intro) Calling conventions Storage classes vs. scope Library functions Overloading.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 10 Java Fundamentals Objects/ClassesMethods.
Chapter 6 Modularity Using Functions
Unit 10 Code Reuse. Key Concepts Abstraction Header files Implementation files Storage classes Exit function Conditional compilation Command-line arguments.
BIL 104E Introduction to Scientific and Engineering Computing Lecture 4.
Functions.
Chapter 7: User-Defined Functions II
Introduction to C++ Systems Programming.
User-Defined Functions
6 Functions.
C++ for Engineers and Scientists Second Edition
Chapter 5 - Functions Outline 5.1 Introduction
6 Chapter Functions.
Classes and Objects.
Chapter 9: Value-Returning Functions
Predefined Functions Revisited
Presentation transcript:

2Object-Oriented Program Development Using C++

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

4Object-Oriented Program Development Using C++ Figure 7-1 A Function as a Machine

5Object-Oriented Program Development Using C++ Figure 7-2 Calling and Passing Data to a Function

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);

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);

8Object-Oriented Program Development Using C++ Figure 7-3 findMax() Receives Actual Values

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

10Object-Oriented Program Development Using C++ Figure 7-4 General Format of a Function

11Object-Oriented Program Development Using C++ Figure 7-5 Storing Values into Parameters

12Object-Oriented Program Development Using C++ Figure 7-6 Structure of a Function Body

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

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

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

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

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

18Object-Oriented Program Development Using C++ Figure 7-7 A Function Can Be Considered a Closed Box

19Object-Oriented Program Development Using C++ Figure 7-8 The Three Storage Areas Created by Program 7-7

20Object-Oriented Program Development Using C++ Figure 7-9 Relating the Scope and Type of a Variable

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;

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

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

24Object-Oriented Program Development Using C++ Figure 7-10 Example of Class Scope

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

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

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

28Object-Oriented Program Development Using C++ Figure 7-12 Extending the Scope of a Global Variable

29Object-Oriented Program Development Using C++ Figure 7-13 Sharing the Static Class Variable taxRate

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

31Object-Oriented Program Development Using C++ Figure 7-15 The Equivalence of Actual and Formal Arguments in Program 7-13

32Object-Oriented Program Development Using C++ Figure 7-16 Relationship Between Arguments and Parameters

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

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

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

36Object-Oriented Program Development Using C++ Figure 7-18 The Stack for the First Call to factorial()

37Object-Oriented Program Development Using C++ Figure 7-19 The Stack for the Second Call to factorial()

38Object-Oriented Program Development Using C++ Figure 7-20 The Stack for the Third Call to factorial()

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

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

41Object-Oriented Program Development Using C++ Table 7-1 Exception Handling Terminology

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;

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

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

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