0% found this document useful (0 votes)
43 views47 pages

Functions Unit 2

The document outlines the fundamentals of Object Oriented Programming (OOP) in C++, focusing on functions, their definitions, declarations, and various types of arguments. It discusses concepts such as passing by value and reference, function overloading, and the use of inline functions. Additionally, it covers variable scope, storage classes, and the differences between local and global variables.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
43 views47 pages

Functions Unit 2

The document outlines the fundamentals of Object Oriented Programming (OOP) in C++, focusing on functions, their definitions, declarations, and various types of arguments. It discusses concepts such as passing by value and reference, function overloading, and the use of inline functions. Additionally, it covers variable scope, storage classes, and the differences between local and global variables.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 47

R section (CSE201R01)

OBJECT ORIENTED PROGRAMMING IN C++


Unit1
Introduction: Fundamentals of object oriented programming -
procedure oriented programming vs. Object Oriented
Programming (OOP), Characteristics of Object Oriented
Programming. C++ Programming Basics: Output using cout,
directives, input with cin, type bool, Manipulators, type
conversions. Functions: Returning values from functions, reference
arguments, overloaded functions, inline functions, default
arguments, returning by reference
R section (CSE201R01)
OBJECT ORIENTED PROGRAMMING IN C++

Unit1
Functions: Returning values from functions, reference
arguments, overloaded functions, inline functions, default
arguments, returning by reference
FUNCTIONS
Functions Definition
• A function can group a number of
program statements into a unit
• functions are used to bring the
conceptual organization of a
program.
Why Function Definition???
• To reduce program size.
• The function’s code is stored
in only
one place in memory
• Even, the function is executed many
times in the course of the program
FUNCTIONS
FUNCTIONS
Simple Functions
• Our first example demonstrates a simple function whose purpose is to print a line
of 45 asterisks. And generates a table
• lines of asterisks are used to make the table more readable.
FUNCTIONS
Function Declaration
• Function declarations are also called prototypes
• The information in the declaration contains the return type and the number and types of
any arguments is also sometimes referred to as the function signature.
void starline();
Calling the Function
• The function is called (or invoked, or executed) three times from main(). Each of the three
calls looks like this:
SYNTAX starline();
• The function name, followed by parentheses.
• The syntax of the call is very similar to that of the declaration, except that the return type is
not used.
• The call is terminated by a semicolon.
• Executing the call statement causes the function to execute; that is, control is transferred to
the
function, the statements in the function definition
FUNCTIONS
Function Definition
• The function itself, which is referred to as the function definition.
• The definition contains the actual code for the function.
• Here’s the definition for starline():

• The definition consists of a line called the declarator, followed by the function
body.
• The function body is composed of the statements that make up the function,
delimited by braces.
• The declarator must agree with the declaration: It must use the same function
name, have the same argument types in the same order (if there are
arguments), and have the same return type.
• Notice that the declarator is not terminated by a semicolon.
FUNCTIONS
Comparison with Library Functions - ch = getche();
Where are the declaration and definition for this library function?
• Declaration is in the header file specified at the beginning of the program (CONIO.H, for getche()).
• The definition (compiled into executable code) is in a library file that’s linked automatically to
your program when you build it.
• When we use a library functions, we don’t need to write the declaration or definition.
• In our own functions, the declaration and definition are part of our source file
Eliminating Declaration
• The second approach to insert a function into a program which eliminate the function declaration
• This approach is simpler for short programs, in that it removes the declaration, but it is less
flexible.
• To use this technique when there are more than a few functions, the programmer must give
considerable thought to arranging the functions so that each one appears before it is called by
any other.
• Sometimes this is impossible; many programmers prefer to place main() first in the listing, since
it is
FUNCTIONS
Simple Function Example
FUNCTIONS
Passing Arguments to functions
• An argument is a piece of data (for eg: an int value) passed from a program to the function.
• Arguments allow a function to operate with different values, or even to do different things,
depending on the requirements of the program calling it.
Passing Constants
• The variables used within the function to hold the argument values are called parameters
in repchar() they are ch and n.

• Placing them in the declarator is equivalent to defining them with statements like
char ch;
int n;
FUNCTIONS
Example

In this example, the


arguments were
constants: ‘–’, 43, and
so on.
FUNCTIONS
Passing Variables
• This program, VARARG, incorporates the same repchar() function as did TABLEARG, but lets the
user specify the character and the number of times it should be repeated.

Output
Enter a character: *
Enter number of times to repeat it:
10
FUNCTIONS
Passing by Value
• The function gives these new variables the names and data types of
the parameters specified in the declarator: ch of type char and n
of type int.
• It initializes these parameters to the values passed.
• They are then accessed like other variables by statements in the
function body.
• Passing arguments in this way, where the function creates copies of
the arguments passed to it, is called passing by value
FUNCTIONS
FUNCTIONS
Structures as Arguments

Entire structures can be


passed as arguments
to functions.
FUNCTIONS
Passing a circle structure

• Console Graphics Lite Function


FUNCTIONS
Names in the Declaration (function)
• Insert meaningful names while declaring, along with the data types.
•To increase the clarity of your function
declarations Example:
void display_point(int, int); // declaration
with only datatype
(Or)
void display_point(int horiz, int vert);
//declaration (better approach)
• The first approach, with (int, int), doesn’t contain
any hint about which argument is for the
vertical coordinate and which is for the horizontal
coordinate.
• The advantage of the second approach is clarity for the programmer: Anyone seeing
this declaration is more likely to use the correct arguments when calling the function.
FUNCTIONS
Returning Values from Function
• When a function completes its execution, it can return a single value
to the calling program.

• Usually this return value consists of an answer to the problem the


function has solved.

• When a function returns a value, the data type of this value must be
specified.

• The function declaration does this by placing the data type, float in
this case, before the function name in the declaration and
the definition.
FUNCTIONS
Returning Values from Function
FUNCTIONS
The return Statement
• While many arguments may be sent to a function, only one argument may
be returned from it.
• This is a limitation when you need to return more information
(call by value)
• There are other approaches to returning multiple variables from
functions.
• One is to pass arguments by reference
• Another is to return a structure with the multiple values as members
• Always include a function’s return type in the function declaration.
• If the function doesn’t return anything, use the keyword void to
indicate this fact.
• If you don’t use a return type in the declaration, the compiler will
assume that the function returns an int value
FUNCTIONS
Eliminating Unnecessary
Variables (in main function)
• The previous program contains
several variables that are used in
the interest of clarity but are not
really necessary.

• A variation of this program,


CONVERT2, shows how expressions
containing functions can often be
used in place of variables.
FUNCTIONS
Returning Structure Variables
FUNCTIONS
Reference Arguments
• Reference arguments are indicated by the ampersand (&)
• It’s actually the memory address of the variable that is passed
• When arguments are passed by value, the called function creates a new variable of the same type
as the argument and copies the argument’s value into it.
• The function cannot access the original variable in the calling program, only the copy it created.
• Passing arguments by value is useful when the function does not need to modify the
original variable in the calling program.
• In fact, it offers the function cannot harm the original variable.
• Passing arguments by reference uses a different mechanism.
• Instead of a value being passed to the function, a reference to the original variable, in the calling
program, is passed
• An important advantage: the function can access the actual variables in the calling program.
• This provides a mechanism for passing more than one value from the function back to the
calling
program
FUNCTIONS
Reference arguments (separation of integer & fraction part )
FUNCTIONS
Reference arguments (separation of integer & fraction part )
FUNCTIONS
Example : Reference arguments (Sort the number pair in ascending order )
FUNCTIONS
Passing by Reference
FUNCTIONS
Notes on Passing by Reference
• References don’t exist in C, where pointers serve a somewhat similar purpose,
although often less conveniently.

• Reference arguments were introduced into C++ to provide flexibility in a variety


of situations involving objects as well as simple variables.

• The third way to pass arguments to functions, besides by value and by reference,
is to use pointers.
FUNCTIONS
Overloaded Functions
• An overloaded function appears to perform different activities depending on the
kind of data sent to it.
• Itperforms one operation on one kind of data but another operation on
a different kind.
• The function name is same but each function have different arguments.
• Overloaded functions can simplify the programmer’s life by reducing the number
of function names to be remembered
Example
FUNCTIONS

Several functions with the same name but


different numbers of arguments.
FUNCTIONS
Different Kinds (Types) of Arguments-Example
FUNCTIONS
Additional examples
FUNCTIONS
Function overloading using classes
FUNCTIONS
Recursion (It involves a function calling itself. )
FUNCTIONS
Function
• Functions save memory space because all the calls to the function cause the same code to be
executed.
• The function body need not be duplicated in memory
• When the compiler sees a function call, it normally generates a jump to the function. At the
end of the function it jumps back to the instruction following the call
•While this sequence of events may save memory space, it takes some extra
time. Inline function
• It’s easy to make a function inline: All you need is the keyword inline in the
function definition
• To save execution time in short functions, put the code in the function body directly inline
with the code in the calling program
• Each time there’s a function call in the source file, the actual code from the function
is inserted, instead of a jump to the function
• This kind of function is written like a normal function in the source file but compiles
into
FUNCTIONS
Difference between inline function and function
Feature Inline Function Normal Function
Definition Defined with the inline keyword, suggesting to A standard function where the
the compiler to insert the function’s code compiler generates a function call
directly at the call site. instead of expanding the code inline.
Eliminates the overhead of a function call by Includes the overhead of function calls,
Performance directly inserting the function code at the call like pushing arguments onto the stack
site (faster for small functions). and jumping to the function.
Usage Best for small and frequently used functions Suitable for larger and more complex
(e.g., getters, setters). functions.
Keyword Requires the inline keyword. However, it’s just a No special Keyword
suggestion; the compiler may ignore it.

Code size Can increase the overall binary size if Keeps the binary size smaller because
used excessively (code duplication at call sites). the code is not duplicated.
Recursion Inline functions cannot be effectively recursive Normal functions can handle recursion
because inlining would require infinite code seamlessly.
expansion.
FUNCTIONS
FUNCTIONS
Inline function- example
Normal function and Inline function
FUNCTIONS
Another example
FUNCTIONS
Default Arguments
• a function can be called without
specifying all its arguments
• This won’t work on just any
function
• The function declaration must
provide default values for
those arguments that are not
specified.
FUNCTIONS
Scope and Storage class
• Scope of a variable determines which parts of the program can access it,
• its storage class determines how long it stays in existence.
• Two different kinds of scope are important here: local and file.
• Variables with local scope are visible only within a block.
• Variables with file scope are visible throughout a file.
• There are two storage classes: automatic and static
• Variables with storage class automatic exist during the lifetime of the function in which
they’re defined.
• Variables with storage class static exist for the lifetime of the program
Local Variable
• A local variable is not created until the function in which it is defined is called.
• Variables defined within any block of code are not created until the block is executed.
• Thus, variables defined within a loop body only exist while the loop is executing.
FUNCTIONS

• The name automatic is used because the variables are


automatically created when a function is called
and automatically destroyed when it returns.
• The time period between the creation and destruction
of a variable is called its lifetime (or sometimes
its duration).
• The lifetime of a local variable coincides with the time
when the function in which it is defined is executing.
• variable’s scope, also called visibility, describes the
locations within a program from which it can
be accessed.
• Variables defined within a function are only visible,
meaning they can only be accessed, from within
the function in which they are defined
FUNCTIONS
Initialization
• When a local variable is created, the compiler does not try to initialize it.
• Thus, it will start off with an arbitrary value, which may be 0 but probably will be
something else, random or garbage values
•If you want it initialized, you must initialize it explicitly, as int n =
33; Global Variable
• The next kind of variable is global.
• It is defined outside of any function
• A global variable is visible to all the functions in a file.
• Global variables are also sometimes called external variables,
(external to any function)
• It will declare outside the main function
• Used when it must be accessible to more than one function in a
program.
• If a global variable is initialized, as in int exvar = 199;
• If a global variable is not initialized explicitly by the program it is
initialized automatically to 0 when it is created
• Global variables have storage class static, which means they exist for the life of
FUNCTIONS
Static Local Variables
• A static local variable has the visibility
of an automatic local variable
• its lifetime is the same as that of a
global
variable
• When static variables are initialized, the
initialization takes place only once—
the first time their function is called.
• They are not reinitialized on subsequent
calls to the function, as ordinary local
variables are.
FUNCTIONS
Storage Types
FUNCTIONS
Example
Returning by Reference
• Allow you to use a function call on the left
side of the equal sign.
• It also make use of a global variable
Example
• The function setx() returns a reference to
the variable x. When this function is
called, it’s treated as the variable x.
• Can’t return a constant from a function
that returns by reference
You cannot do this
FUNCTIONS
Const Function Arguments
• passing an argument by
reference can be used to
allow a function to modify a
variable in the calling
program.
• pass an by
argument
reference gives efficiency,
and if you want the function
not to modify it.

You might also like