You are on page 1of 66

FUNCTION IN C++

(LECTURE 3-4)

Satyendra Singh Chouhan


Assistant professor (CSE)
2

Agenda
• What is a function? • Sharing data among
• Types of C++ functions: functions through
• Standard functions function parameters
• User-defined functions • Value parameters
• Reference parameters
• C++ function structure
• Const reference
• Function signature
parameters
• Function body
• Scope of variables
• Declaring and
• Local Variables
Implementing C++ • Global variable
functions
3

Outline
A basic function in C++ looks similar to the function in C.

For a quick overview for basic function syntax, inbuilt


functions (provided by different libraries for e.g., <cmath>,
<stdlib>, etc

See function_basic.ppt in …/B7B8B9/Extra_material folder

In this lecture we will discuss the some special functions


such as inline function, static function, also constructor and
destructor.
Formatted i/o
• Unformatted Input/Output(I/O) is the most basic form of

input/output.

• Unformatted I/O transfers the internal binary representation of

the data directly between memory and the file.

• Formatted i/p converts the internal binary representation of the

data to ASCII characters which are written to the o/p file.

• Formatted I/p reads characters from the input file and converts

them to internal form. Formatted I/O can be either "Free"


format or "Explicit" format.
Formatted i/0
Setw setw that sets the width to print in the output.

width() ‘This function also takes the same parameter and an


integer, in which width the things are to display or read
Setprecisio This is the parameterized, inline- manipulator
n that sets the places after the decimal point. There is a
member function as well in these objects that is precision. The
setprecision is an inline manipulator, used along with stream
insertion (<<)
6

Unformatted i/o
• cout, cin
• getline (name_of_variable, size);
• Examples : cin.getline (title,256);
7

User – Defined Data Type


• C++ supports a feature of “type definition” that allows user to define an
identifier that would represent an existing data type.
• User – defined data type identifier can later be used to declare variables
such as:
 typedef
 enum (enumerated)

• The general form for given above user – defined data type is as follows:

typedef datatype identifier;

Example: typedef int feet;


feet a=10;
User-Defined Data Types
 Structures and Classes
◦ Basis for OOP.
◦ Classes enable to combine data and procedures.
 Enumerated Data Type
◦ It provides a way to attaching names to the numbers
◦ Increase comprehensibility of the code.
◦ Alternative mean for creating symbolic constants
◦ Enumerates a list of words by assigning them values
0,1,2 and so on.

enum shape {circle, square, triangle};


enum colour {red, blue=4, green=8};
9

Global Variable
10

Example of Defining and Using Global


and Local Variables
#include <iostream.h>
int x; // Global variable
Void fun(); // function signature

void main()
{
x = 4;
fun();
cout << x << endl;
}

void fun()
{
int x = 10; // Local variable
cout << x << endl;
}
11

Example of Defining and Using Global


and Local Variables
#include <iostream.h> x 0
int x; // Global variable
Void fun(); // function signature Global variables are
automatically initialized to 0
void main()
{
x = 4;
fun();
cout << x << endl;
}

void fun()
{
int x = 10; // Local variable
cout << x << endl;
}
12

Example of Defining and Using Global


and Local Variables
#include <iostream.h> x 0
int x; // Global variable
Void fun(); // function signature

void main()
{
x = 4;
fun();
cout << x << endl;
}

void fun() void main()


{ {
int x = 10; // Local variable 1 x = 4;
cout << x << endl; fun();
cout << x << endl;
}
}
13

Example of Defining and Using Global


and Local Variables
#include <iostream.h> x 4
int x; // Global variable
Void fun(); // function signature

void main() void fun()


{
x ????
x = 4;
fun(); {
cout << x << endl; 3 int x = 10;
cout << x << endl;
}
}

void fun() void main()


{ {
int x = 10; // Local variable x = 4;
cout << x << endl; 2 fun();
cout << x << endl;
}
}
14

Example of Defining and Using Global


and Local Variables
#include <iostream.h> x 4
int x; // Global variable
Void fun(); // function signature

void main() void fun()


{
x 10
x = 4;
fun(); {
cout << x << endl; 3 int x = 10;
cout << x << endl;
}
}

void fun() void main()


{ {
int x = 10; // Local variable x = 4;
cout << x << endl; 2 fun();
cout << x << endl;
}
}
15

Example of Defining and Using Global


and Local Variables
#include <iostream.h> x 4
int x; // Global variable
Void fun(); // function signature

void main()
{ void fun()
x = 4; x 10
fun();
cout << x << endl; {
} int x = 10;
4 cout << x << endl;
void fun() }
{ void main()
int x = 10; // Local variable {
cout << x << endl; x = 4;
} 2 fun();
cout << x << endl;
}
16

Example of Defining and Using Global


and Local Variables
#include <iostream.h> x 4
int x; // Global variable
Void fun(); // function signature

void main()
{ void fun()
x = 4; x 10
fun();
cout << x << endl; {
} int x = 10;
cout << x << endl;
void fun() 5 }
{ void main()
int x = 10; // Local variable {
cout << x << endl; x = 4;
} 2 fun();
cout << x << endl;
}
17

Example of Defining and Using Global


and Local Variables
#include <iostream.h> x 4
int x; // Global variable
Void fun(); // function signature

void main()
{
x = 4;
fun();
cout << x << endl;
}

void fun()
{ void main()
int x = 10; // Local variable {
cout << x << endl; x = 4;
} fun();
6 cout << x << endl;
}
18

Example of Defining and Using Global


and Local Variables
#include <iostream.h> x 4
int x; // Global variable
Void fun(); // function signature

void main()
{
x = 4;
fun();
cout << x << endl;
}

void fun()
{ void main()
int x = 10; // Local variable {
cout << x << endl; x = 4;
} fun();
cout << x << endl;
7 }
Function Call Stack and Activation Records

• To understand how C++ performs function calls, we first need


to consider a data structure (i.e., collection of related data
items) known as a stack.
• Analogous to a pile of dishes.
• When a dish is placed on the pile, it’s normally placed at the top—
referred to as pushing.
• Similarly, when a dish is removed from the pile, it’s normally removed
from the top—referred to as popping.
• Last-in, first-out (LIFO) data structures—the last item pushed
(inserted) is the first item popped (removed).
Function Call Stack and Activation Records (cont.)

• Function-Call Stack

• One of the most important mechanisms for computer science


students to understand is the function call stack (or program
execution stack).
• supports the function call/return mechanism.

• Also supports the creation, maintenance and destruction of each called


function’s automatic variables.
Function Call Stack and Activation Records (cont.)

• Stack Frames
• Each function eventually must return control to the function
that called it.
• Each time a function calls another function, an entry is pushed
onto the function call stack.
• This entry, called a stack frame or an activation record, contains the
return address that the called function needs in order to return to the
calling function.
Function Call Stack and Activation Records (cont.)

• Automatic Variables and Stack Frames


• When a function call returns, the stack frame for the function call is
popped, and control transfers to the return address in the popped stack
frame.
• Stack Overflow
• The amount of memory in a computer is finite, so only a certain amount
of memory can be used to store activation records on the function call
stack.
• If more function calls occur than can have their activation records stored
on the function call stack, an a fatal error known as stack overflow
occurs.
Function Call Stack and Activation Records (cont.)

• Function Call Stack in Action


• Now let’s consider how the call stack supports the operation of a square
function called by main (Fig. 1).
• First the operating system calls main - this pushes an activation record
onto the stack (shown in Fig. 2).
• The activation record tells main how to return to the operating system
(i.e., transfer to return address R1) and contains the space for main’s
automatic variable (i.e., a, which is initialized to 10).
Fig 1
Fig 2
6.12 Function Call Stack and Activation Records (cont.)

• Function main -before returning to the operating system—now calls


function square in line 13 of Fig. 1.
• This causes a stack frame for square (lines 17–20) to be pushed onto the
function call stack (Fig. 3).
• This stack frame contains the return address that square needs to return
to main (i.e., R2) and the memory for square’s automatic variable (i.e., x).
Fig 3
6.12 Function Call Stack and Activation Records (cont.)

• After square calculates the square of its argument, it needs to return to


main - and no longer needs the memory for its automatic variable x. So
square’s stack frame is popped from the stack - giving square the return
location in main (i.e., R2) and losing square’s automatic variable.
• Figure 4 shows the function call stack after square’s activation record has
been popped.
Fig 4
6.13 Functions with Empty Parameter Lists

• In C++, an empty parameter list is specified by writing either


void or nothing at all in parentheses.
• Figure 5 shows both ways to declare and use functions with
empty parameter lists.
Fig 5
Fig 6
Inline Function
Inline Functions
• Sometimes, we use the keyword inline to define
user-defined functions
– Inline functions are very small functions, generally, one
or two lines of code
– Inline functions are very fast functions compared to the
functions declared without the inline keyword
• Example
inline double degrees( double radian)
{
return radian * 180.0 / 3.1415;
}
Example #1
• Write a function to test if a number is an odd number

inline bool odd (int x)


{
return (x % 2 == 1);
}
I. Using Global Variables
#include <iostream.h>
int x = 0;
void f1() { x++; }
void f2() { x+=4; f1(); }
void main()
{
f2();
cout << x << endl;
}
I. Using Global Variables
x 0
#include <iostream.h>
int x = 0;
void f1() { x++; }
void f2() { x+=4; f1(); }
void main()
{
f2();
cout << x << endl;
}
I. Using Global Variables
x 0
#include <iostream.h>
int x = 0;
void f1() { x++; }
void f2() { x+=4; f1(); }
void main()
{
f2();
void main()
cout << x << endl; {
} 1 f2();
cout << x << endl ;
}
I. Using Global Variables
x 0
4
#include <iostream.h>
int x = 0;
void f1() { x++; }
void f2() { x+=4; f1(); }
void f2()
void main() {
2 x += 4;
{ f1();
f2(); }
void main()
cout << x << endl; {
} 1 f2();
cout << x << endl ;
}
I. Using Global Variables
x 5
4
#include <iostream.h>
int x = 0; void f1()
{
void f1() { x++; } 4 x++;
}
void f2() { x+=4; f1(); }
void f2()
void main() {
x += 4;
{ 3 f1();
f2(); }
void main()
cout << x << endl; {
} 1 f2();
cout << x << endl ;
}
I. Using Global Variables
x 5
4
#include <iostream.h>
int x = 0; void f1()
{
void f1() { x++; } x++;
5 }
void f2() { x+=4; f1(); }
void f2()
void main() {
x += 4;
{ 3 f1();
f2(); }
void main()
cout << x << endl; {
} 1 f2();
cout << x << endl;
}
I. Using Global Variables
x 5
4
#include <iostream.h>
int x = 0;
void f1() { x++; }
void f2() { x+=4; f1(); }
void f2()
void main() {
x += 4;
{ f1();
f2(); 6 }
void main()
cout << x << endl; {
} 1 f2();
cout << x << endl;
}
I. Using Global Variables
#include <iostream.h> x 5
4

int x = 0;
void f1() { x++; }
void f2() { x+=4; f1(); }
void main()
{
f2();
cout << x << endl; void main()
{
} f2();
7 cout << x << endl;
}
I. Using Global Variables
#include <iostream.h> x 5
4

int x = 0;
void f1() { x++; }
void f2() { x+=4; f1(); }
void main()
{
f2();
cout << x << endl; void main()
{
} f2();
cout << x << endl;
8 }
I. Using Global Variables
#include <iostream.h>
int x = 0;
void f1() { x++; }
void f2() { x+=4; f1(); }
void main()
{
f2();
cout << x << endl;
}
What Happens When We Use Inline
Keyword?
#include <iostream.h>
int x = 0;
Inline void f1() { x++; }
Inline void f2() { x+=4; f1();}
void main()
{
f2();
cout << x << endl;
}
What Happens When We Use Inline
Keyword?
#include <iostream.h> x 0

int x = 0;
Inline void f1() { x++; } The inline keyword
instructs the compiler
Inline void f2() { x+=4; f1();} to replace the function
call with the function
void main() body!
{
f2();
void main()
cout << x << endl; {
1 x+=4;
} x++;
cout << x << endl;
}
What Happens When We Use Inline
Keyword?
#include <iostream.h> x 4

int x = 0;
Inline void f1() { x++; }
Inline void f2() { x+=4; f1();}
void main()
{
f2();
void main()
cout << x << endl; {
x+=4;
} 2 x++;
cout << x << endl;
}
What Happens When We Use Inline
Keyword?
#include <iostream.h> x 5

int x = 0;
Inline void f1() { x++; }
Inline void f2() { x+=4; f1();}
void main()
{
f2();
void main()
cout << x << endl; {
x+=4;
} x++;
3 cout << x << endl;
}
What Happens When We Use Inline
Keyword?
#include <iostream.h> x 5

int x = 0;
Inline void f1() { x++; }
Inline void f2() { x+=4; f1();}
void main()
{
f2();
void main()
cout << x << endl; {
x+=4;
} x++;
cout << x << endl;
4 }
What Happens When We Use Inline
Keyword?
#include <iostream.h>
int x = 0;
Inline void f1() { x++; }
Inline void f2() { x+=4; f1();}
void main()
{
f2();
cout << x << endl;
}
Static Function Member
STATIC FUNCTION MEMBERS

• We can define class members static using static


keyword.

• When we declare a member of a class as static it means

no matter how many objects of the class are created,


there is only one copy of the static member.

• A static member is shared by all objects of the class.


STATIC FUNCTION MEMBERS

• All static data is initialized to zero

• When the first object is created, if no other initialization is

present. We can't put it in the class definition but it can be


initialized outside the class as done in the following
example by redeclaring the static variable, using the
scope resolution operator :: to identify which class it
belongs to.
STATIC FUNCTION MEMBERS
• By declaring a function member as static, you make it
independent of any particular object of the class.
• A static member function can be called even if no objects
of the class exist and the static functions are accessed
using only the class name and the scope resolution
operator ::.
• A static member function can only access static data
member, other static member functions and any other
functions from outside the class.
• You could use a static member function to determine
whether some objects of the class have been created or
not.
class test
{
static int i;
public: void static geti() { ++i; }
void printi() { cout<<"\n i val is = "<<i; }
};
int test :: i=0; // needs to be initilized.
void main()
{
clrscr();
test t1, t2;
t1.geti();
t2.geti();
t1.printi();
getch();
}
FRIEND FUNCTION
FRIEND FUNCTION

• A friend function of a class is defined outside that class'


scope but it has the right to access all private and
protected members of the class.
• Even though the prototypes for friend functions appear in
the class definition, friends are not member functions.
• To declare a function as a friend of a class, precede the
function prototype in the class definition with
keyword friend as follows:

friend return_type friend_function_name(class_name, &obj);


FRIEND FUNCTION
• Friend functions are not member functions of the class.

• The class itself declares the friend functions.

• These functions have access to the private data member

of the class, which means they have access to everything


in the class.

• In friend function we pass an object of class as a

arguments to access the data.

• Normally we write friend functions at the top of the class

definition.
FRIEND FUNCTION
class myclass
{
friend void buddy(myclass,int);
private:
int c;
public:
void display()
{
cout<<"the value of private variable is :” <<c<<endl;
}
};
Some Important concepts in C++
Review: What = and & Mean
• In C++ the = symbol means either initialization or assignment
• If it’s used with a type declaration, it means initialization
• If it’s used without a type declaration, it means assignment
int j(7); // j is initialized with value 7
int k = 4; // k is initialized with value 4
j = 3; // j is assigned value 3

• In C++ the & symbol also has a similar “dual nature”


• If it’s used inside a type declaration, it means a reference (an alias)
• Arguments to function are always declared along with their types
• If it’s used outside a type declaration, it means “address of”
int swap (int & i, int & j); // references to int
int & s = j; // reference s initialized to refer to j
int * p = & j; // pointer p initialized w/ j’s address
Default Arguments

• Some functions can take several arguments


• Can increase function flexibility
• Can reduce proliferation of near-identical functions

• But, callers must supply all of these arguments


• Even for ones that aren’t “important”

• We can provide defaults for some arguments


• Caller doesn’t have to fill these in
Required vs. Default Arguments
• Function with required argument

// call as foo(2); (prints 2)


void foo(int a);
void foo(int a) {cout << a << endl;}

• Function with default argument


• Notice only the declaration gives the default value

// can call as foo(2); (prints 2)


// or can call as foo(); (prints 3)
void foo(int a = 3);
void foo(int a) {cout << a << endl;}
Defaults with Multiple Arguments
• Function with one of two arguments defaulted

// can call as foo(2); (prints 2 3)


// or can call as foo(2, 4); (prints 2 4)
void foo(int a, int b = 3);
void foo(int a, int b)
{cout << a << “ ” << b << endl;}

• Same function, with both arguments defaulted

// can call as foo(); (prints 1 3)


// or can call as foo(2); (prints 2 3)
// or can call as foo(2, 4); (prints 2 4)
void foo(int a = 1, int b = 3);
void foo(int a, int b)
{cout << a << “ ” << b << endl;}
Default Argument Limitations

• Watch out for ambiguous signatures


• foo(); and foo(int a = 2); for example

• Can only default the rightmost arguments


• Can’t declare void foo(int a = 1, int b);

• Caller must supply leftmost arguments


• Even if they’re the same as the defaults

You might also like