0% found this document useful (0 votes)
4 views

Lecture 512

The document provides an overview of functions in C++, including their types, declaration, definition, and calling methods. It discusses concepts such as recursion, default arguments, scope rules, and function overloading, highlighting the importance of functions in organizing code and reducing redundancy. Additionally, it covers argument passing techniques and the advantages and disadvantages of recursion.
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)
4 views

Lecture 512

The document provides an overview of functions in C++, including their types, declaration, definition, and calling methods. It discusses concepts such as recursion, default arguments, scope rules, and function overloading, highlighting the importance of functions in organizing code and reducing redundancy. Additionally, it covers argument passing techniques and the advantages and disadvantages of recursion.
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/ 96

CSE202: OBJECT ORIENTED PROGRAMMING

Functions
Recursion
Default Arguments
Scope Rules
Function Overloading
Static Members and Static Functions
Friend Function and Friend Class
What is function????

• Function is a self contained block of statements that


perform a coherent task of some kind.
• Every C++ program can be a thought of the
collection of functions.
• main( ) is also a function.
Types of Functions.

• Library functions
– These are the in- -built functions of ‘C++ ’library.
– These are already defined in header files.
– e.g. Cout<<; is a function which is used to print at output.
It is defined in ‘iostream.h ’ file .
• User defined functions.
– Programmer can create their own function in C++ to
perform specific task
Why use function?
• Writing functions avoids rewriting of the same code
again and again in the program.
• Using function large programs can be reduced to
smaller ones. It is easy to debug and find out the
errors in it.
• Using a function it becomes easier to write program
to keep track of what they are doing.
//Function Declaration
retn_type func_name(data_type 1,data_type par2);

//Function Defination
rent_type func_name(data_type par1,data_type par2)
{
// body of the function
}

//Function Call
func_name(par1,par2);
Function prototype

• A prototype statement helps the compiler to check


the return type and arguments type of the function.
• A prototype function consist of the functions return
type, name and argument list.
• Example
– int sum( int x, int y);
Example
#include<iostream.h>
#include<conio.h>
void sum(int, int); // function declaration
main()
{
int a, b;
cout<<“enter the two no”;
cin>>a>>b;
sum(a,b); // function calling

}
void sum( int x, int y) // function definition
{
int c=x+y;
cout<< “ sum is”<<c;
}
#include<conio.h>
int sum(int, int);
main()
{
int a=10,b=20;
int c=sum(a,b); /*actual arguments
Cout<<“sum is” << c;
getch();
}
int sum(int x, int y) /*formal arguments
{
int s;
s=x+y;
return(s); /*return value
}
Where does the execution of the
program starts?
a) user-defined function
b) main function
c) void function
d) else function
What are mandatory parts in the
function declaration?
a) return type, function name
b) return type, function name, parameters
c) parameters, function name
d) parameters, variables
What is the scope of the variable
declared in the user defined function?
a) whole program
b) only inside the {} block
c) the main function
d) header section
Categories of functions

🞂 A function with no parameter and no return value


🞂 A function with parameter and no return value
🞂 A function with parameter and return value
🞂 A function without parameter and return value
A function with no parameter and no return value
#include<iostream>
using namespace std;
int main()
{
void print(); /*func declaration
cout<<“no parameter and no return value”;
print(); /*func calling
}
void print() /*func definition
{
for(int i=1;i<=30;i++)
{
cout<<“*”;
}
Cout<<“\n”;
}
A function with no parameter and no return value

• There is no data transfer between calling and called


function
• The function is only executed and nothing is
obtained
• Such functions may be used to print some
messages, draw stars etc
A function with parameter and no return value

#include<iostream>
using namespace std;
int main()
{
int a=10,b=20;
void mul(int,int);
mul(a,b); /*actual arguments
getch();
}
void mul(int x, int y) /*formal arguments
{
int s;
s=x*y;
cout<<“mul is” << s;
}
A function with parameter and return value

#include<iostream>
using namespace std; int max(int x, int y)
int main() {
if(x>y)
{ return(x);
else
int a=10,b=20,c; {
return(y);
int max(int,int); }
}
c=max(a,b);
cout<<“greatest no is” <<c;
}
A function without parameter and return value
#include<iostream>
using namespace std;

int main()
{
int a=10,b=20;
int sum();
int c=sum(); /*actual arguments
Cout<<“sum is”<< c;
}
int sum() /*formal arguments
{
int x=10,y=20;
return(x+y); /*return value
}
What is the default return
type of a function ?
A. int
B. void
C. float
D. char
What is the output of this program?

#include < iostream >


using namespace std;
void fun(int x, int y)
{
x = 20;
y = 10;
}
int main()
{
int x = 10;
fun(x, x);
cout << x;
return 0;
}
•A. 10
•B. 20
•C. compile time error
•D. none of the mentioned
#include < iostream >
using namespace std;
int fun(int x, int y)
{
x = 20;
y = 10;
return x; A. A function with no parameter and no return
} value
int main()
{
B. A function with parameter and no return
int x = 10; value
x=fun(x, x); C. A function with parameter and return value
cout << x;
return 0;
D. A function without parameter and return
} value
Argument passing techniques

• Pass/or Call By Value


• Pass/or Call By Pointer/Address
• Pass/or Call By Reference
Call By Value

• It is a default mechanism for argument passing.


• Any changes made in the formal argument are not
reflected back to actual argument, rather they
remain local to the block which are lost once the
control is returned back to calling program
EXAMPLE

int main()
{
int a=10,b=20;
void swap(int,int);
Cout<<“before function calling”<<a<<b;
swap(a,b);
Cout<<“after function calling”<<a<<b;
}
void swap(int x,int y)
{
int z;
z=x;
x=y;
y=z;
Cout<<“value is”<<x<<y;
}
Output:
before function calling a=10 b=20
value of x=20 and y= 10
after function calling a=10 b=20
Call By pointer/address

• In this instead of passing value, address are passed.


• Here formal arguments are pointers to the actual
arguments
• Hence change made in the argument are
permanent.
int main()
{
int a=10 ,b=25;
void swap(int *,int *);
Cout<<“before function calling”<<a<<b;
swap(&a,&b);
Cout<<“after function calling”<<a<<b;
}
void swap(int *x,int *y)
{
int z;
z=*x;
*x=*y;
*y=z;
Cout<<“value is”<<*x<<*y;
}
Output:

before function calling a= 10 b= 25


value of x=25 and y=10
after function calling a=25 b= 10
Call By Reference(Using Reference Variables
with Functions)

• To create a second name for a variable in a


program, you can generate an alias, or an alternate
name

• In C++ a variable that acts as an alias for another


variable is called a reference variable, or simply a
reference
Declaring Reference Variables

🞂 You declare a reference variable by placing a type


and an ampersand in front of a variable name, as in
double &cash; and assigning another variable
of the same type to the reference variable
double someMoney;
double &cash = someMoney;

🞂 A reference variable refers to the same memory


address as does a variable, and a pointer holds the
memory address of a variable
EXAMPLE REFERENCE VARIABLE

int main()
{
int i=10;
int &j=i; // j is a reference variable of I
cout<<“value”<<i<<“\t”<<j;
j=20;
cout<<“modified value”<<i<<“\t”<<j;
}
Output:-
Value 10 10
modified value 20 20
PASS BY REFERENCE

int main()
{
int a=10 ,b=25;
void swap(int &a, int &b);
cout<<“before function calling”<<a<<b;
swap(a, b);
cout<<“after function calling”<<a<<b;
}
void swap(int &x, int &y)
{
int z;
z=x;
x=y;
y=z;
cout<<“value is”<<*x<<*y;
}
Output:

before function calling a= 10 b= 25


value of x=25 and y=10
after function calling a=25 b= 10
Find output:
#include<iostream>
using namespace std;
main()
{
int a=10,b=2;
void swap(int,int);
cout<<"before calling their values are "<<a<<" "<<b;
swap(a,b);
cout<<"\nafter calling their values are "<<a<<" "<<b;
}
void swap(int x, int y) a. before calling their values are 10 2
{ after calling their values are 10 2
int z; b. before calling their values are 10 2
z=x; after calling their values are 2 10
x=y; c. before calling their values are 10 2
y=z; after calling their values are 10 10
} d. before calling their values are 2 10
after calling their values are 10 2
Find output:
#include<iostream>
using namespace std;
main()
{
int a=10,b=2;
void swap(int *,int *);
cout<<"before calling their values are "<<a<<" "<<b;
swap(&a,&b);
cout<<"\nafter calling their values are "<<a<<" "<<b;
}
void swap(int *x, int *y) a. before calling their values are 10 2
{ after calling their values are 10 2
int z; b. before calling their values are 10 2
z=*x; after calling their values are 2 10
*x=*y; c. before calling their values are 10 2
*y=z; after calling their values are 10 10
} d. before calling their values are 2 10
after calling their values are 10 2
Recursion

🞂 When function call itself repeatedly ,until some


specified condition is met then this process is called
recursion.
🞂 It is useful for writing repetitive problems where
each action is stated in terms of previous result.
🞂 The need of recursion arises if logic of the problem
is such that the solution of the problem depends
upon the repetition of certain set of statements
with different input values an with a condition.
(EXAMPLE)Factorial using recursion

int main() int rec(int a)


{ {
int b;
int rec(int);
if(a<=1)
int n, fact;
{
cout<<“enter the no.”;
return(1);
cin>>n;
}
fact=rec(n); else
cout<<“factorial is”<<fact; {
} b=a*rec(a-1);
return(b);
Advantages of recursion

1. It make program code compact which is easier to


write and understand.
2. It is used with the data structures such as linklist,
stack, queues etc.
3. It is useful if a solution to a problem is in repetitive
form.
4. The compact code in a recursion simplifies the
compilation as less number of lines need to be
compiled.
Disadvantages

1. Consume more storage space as recursion calls


and automatic variables are stored in a stack.
2. It is less efficient in comparison to normal program
in case of speed and execution time
3. Special care need to be taken for stopping
condition in a recursion function
4. If the recursion calls are not checked ,the
computer may run out of memory.
Default arguments

• In the function prototype declaration , the default


values are given. Whenever a call is made to
function without specifying an argument , the
program will automatically assign values to the
parameters from the default function prototype.
• Default arguments facilitate easy development and
maintenance of programs.
#include<iostream>
void sum(int x=10, int y=20);
main()
{
int a, b;
sum();
}
void sum(int a1=10,int a2=20)
{
temp= a1+a2;
}
Default Arguments
#include <iostream> display('$', 5);
using namespace std; return 0;
void display(char = '*', int = 1); }
int main() void display(char c, int n){
{ for(int i = 1; i <=n; ++i) {
cout<<"No argument passed:\n"; cout<<c;
display(); }
cout<<"\n\nFirst argument passed:\ cout<<endl;
n";
}
display('#');
cout<<"\n\nBoth argument passed:\
n";
If the user didn't supply the user
value means, then what value will
it take?
•A. default value
•B. rise an error
•C. both a & b
•D. none of the mentioned
Where does the default parameter
can be placed by the user?
A. leftmost
B. rightmost
C. both a & b
D. none of the mentioned
Which value will it take when both
user and default values are given?
A. user value
B. default value
C. custom value
D. none of the mentioned
SCOPE RULES

🞂 Local Variable
🞂 Global variable
🞂 Local Variables are defined inside the function
body or in a compound statement. The scope of
these variables are inside the function where
they are defined.
Eg: int fact (int n)
{
Int i, fact, j; // i, j are local variables.
-----
----
}
• Global variables are those variables whose scope is
available through out the program.
#include<iostream>

using namespace std;

int x;

main()

int y=0;

{ int y=20;

cout<<endl<<x<<y;

x++;y++;

{ int y=20;

cout<<endl<<x<<y;

}}

cout<<endl<<x<<y;

}
FUNCTION OVERLOADING
Overloading in C++

❑What is overloading
– Overloading means assigning multiple
meanings to a function name or operator
symbol
– It allows multiple definitions of a function with
the same name, but different signatures.
❑C++ supports
– Function overloading
– Operator overloading
Function Overloading

• Is the process of using the same name for two or


more functions
• Requires each redefinition of a function to use a
different function signature that is:
– different types of parameters,
– or sequence of parameters,
– or number of parameters
• Is used so that a programmer does not have to
remember multiple function names
Void sum(int,int);
Void sum(double,double); void sum(int x, int y)
Void sum(char,char); {
cout<<“\n sum of integers are”<<x+y;
main() }
{ void sum(double x, double y)
int a=10,b=20 ; {
cout<<“\n sum of two floating no are”<<x+y;
double c=7.52,d=8.14; }
char e=‘a’ , f=‘b’ ; void sum(char x, char y)
sum(a,b); {
cout<<“\n sum of characters are”<<x+y;
sum(c,d); }
sum(e,f);
}
When will we use the function overloading?
A. same function name but different
number of arguments
B. different function name but same
number of arguments
C. same function name but same number
of arguments
D. different function name but different
number of arguments
Overloaded functions are
A. Very long functions that can
hardly run
B. One function containing another
one or more functions inside it.
C. Two or more functions with the
same name but different number of
parameters or type.
Memory allocation for objects

• We have studied that memory space for objects is


allocated when they are declared and not when class
is specified. All objects belong to a class use same
member functions no separate space is allocated for
member function when object is created.
• Only space for member variables is allocated
separately for each object.
• Memory created when functions defined: common
• Memory created when objects defined. Not common
Static Data Members
• It is initialized to zero when first object of its class is created . No other
initialization is permitted.
• Only one copy of that member is created for entire class and shared by all objects
of that class.
• Visible only within class but lifetime in entire program.
• They are normally used to maintain values common to the entire class
Example: static data member can be used as a counter that records the occurrences of
all objects
• Type and scope of each static member variable must be defined outside the class
definition.
• This is necessary because static data members are stored separately rather than
as a part of an object.
• Since they are associated with the class itself rather than with any class object,
they are also known as class variables.
Static data member
#include<iostream> main(){
using namespace std; item a,b,c;
class item a.getcount();
{ static int count; b.getcount();
int number; c.getcount();
public:
void getdata(int d) a.getdata(100);
{ number = d; b.getdata(200);
count++; c.getdata(300);
}
void getcount() cout<<"\nafter reading\n";
{ a.getcount();
cout<<count; b.getcount();
} c.getcount();
}; }
int item :: count; // definition of static
data member
Static data member(count)
Static member function

A static function can have access to only static


members declared in same class
Can be called using class name instead of objects
class-name :: function-name;
#include<iostream>
using namespace std; int main()
class test {
{
int code; test t1,t2;
static int Scount;
public: t1.setcode();
void setcode()
{ t2.setcode();
code= ++Scount; test :: showcount();
}
void showcode() test t3;
{
cout<<"Code: "<<code<<endl; t3.setcode();
}
test:: showcount();
static void showcount()
{ t1.showcode();
cout<<"Count: "<<Scount<<endl;
} t2.showcode();
};
int test :: Scount; t3.showcode();
}
True statements about static member
function is/are
(I)Static function of a class can be called by
class name using scope resolution operator
i.e. : :
(II)Static function can receive both static and
non-static data members of a class
(III)Static function is not the part of an object of
a class

1.I and II
2.I only
3.I and III
4.I, II and III
True statements about static member
function is/are
(I)Static function of a class can be called by
class name using scope resolution operator
i.e. : :
(II)Static function can receive both static and
non-static data members of a class
(III)Static function is not the part of an object of
a class

1.I and II
2.I only
3.I and III
4.I, II and III
Which function can be called without using an
object of a class in C++

1.Static function
2.Inline function
3.Friend function
4.constant function
Which function can be called without using an
object of a class in C++

1.Static function
2.Inline function
3.Friend function
4.constant function
Friend Functions and Friend Classes
Data hiding is a fundamental concept of object-oriented programming. It restricts the access of
private members from outside of the class.
Similarly, protected members can only be accessed by derived classes and are inaccessible from
outside.
However, there is a feature in C++ called friend functions that break this rule and allow us to
access member functions from outside the class.
Similarly, there is a friend class as well, which we will learn later

• friend function of a class


– Defined outside that class’s scope.
– Not a member function of that class.
– has the right to access the non-public and public members of that class.
– Standalone functions or entire classes may be declared to be friends of a class.
– Can enhance performance.
– Often appropriate when a member function cannot be used for certain operations.
• When we want our private data to be shared by a
non member function
Then
• Basically, we declare something as a friend, you give
it access to your private data members.
• Single functions or entire classes may be declared
as friends of a class.
friend Function in C++
A friend function can access the private and protected
data of a class. We declare a friend function using the
friend keyword inside the body of the class.
class className
{
... .. ...
friend returnType functionName(arguments);
... .. ...
}
A friend function possesses certain special characteristics:
• It is not in the scope of the class to which it has been declared
as friend.
• Since it is not in the scope of the class, it cannot be called
using the object of that class.
• It can be invoked like a normal function without the help of
any object.
• Unlike member functions, it cannot access the member names
directly and has to use an object name and dot membership
operator with each member name (e.g., A.x)
• It can be declared either in public or private part of a class
without affecting its meaning.
• Usually, it has the objects as arguments.
#include<iostream>
using namespace std;
class sample
{
int a,b;
public:
void setvalue() { a=10; b=40; }
friend float mean (sample s);
};
float mean(sample s)
{
return float(s.a + s.b)/2;
}
main()
{
sample x;
x.setvalue();
cout<<"mean is "<< mean(x);
}
• Where does keyword ‘friend’ should be placed?

A. function declaration
B. function definition
C. main function
D. block function
• Where does keyword ‘friend’ should be placed?

A. function declaration
B. function definition
C. main function
D. block function
Example 2: Add Members of Two Different Classes

// Add members of two different classes using friend


functions class ClassB {
private:
#include <iostream> int b;
using namespace std; // friend function declaration
friend int add(ClassA, ClassB);
// forward declaration
class ClassB; public:
void ipb() {b=20;}
class ClassA { }B;
private: // access members of both classes
int a; int add(ClassA objectA, ClassB objectB) {
public: int s;
void ipa() { a=10;} s=objectA.a + objectB.b;
return (s);
// friend function declaration }
friend int add(ClassA, ClassB); main() {
}A; A.ipa(); B.ipb();
cout << "Sum: " << add(A,B);

}
• Which of the following is correct about friend
functions?

A. Friend functions use the dot operator to


access members of a class using class
objects
B. Friend functions can be private or public
C. Friend cannot access the members of
the class directly
D. All of the above
• Which of the following is correct about friend
functions?

A. Friend functions use the dot operator to


access members of a class using class
objects
B. Friend functions can be private or public
C. Friend cannot access the members of
the class directly
D. All of the above
A friend function can be

A. A method of another class


B. A global function
C. Both A and B
D. None of the above
A friend function can be

A. A method of another class


B. A global function
C. Both A and B
D. None of the above
Function friendly to two classes
# include<iostream>
using namespace std;
class ABC; //forward declaration
class XYZ
{
int x; int main()
public: {
void setvalue(int i) { x=i;} ABC abc;
friend void max(XYZ, ABC); abc.setvalue(10);
}; XYZ xyz;
class ABC xyz.setvalue(20)
{ max(xyz,abc);
int a; return 0;
public: }
void setvalue(int i) { a=i;}
friend void max(XYZ, ABC); OUTPUT:
}; 20
void max(XYZ m, ABC n) //Definition of

friend
{
if(m.x>= n.a)
cout<<m.x;
else
cout<<n.a;
}
Swapping Private data of classes
# include<iostream> C1.indata(100);
using namespace std; C2.indata(200);
class class_2;
class class_1 cout<<“Values before exchange”<“\
{ n”;
int value1; C1.display();
public: C2.display();
void intdata(int a) { value1=a;} exchange(C1,C2); //swapping
void display(void) { cout<<value1<<‘\n”; }
friend void exchange(classes_1 &, cout<<“values after exchange”<<“\n”;
classes_2 &); C1.display();
}; C2.display();
void exchange(class_1 & x, class_2 & y) return 0;
{ }
int temp = x.value1; OUTPUT:
x.value1 = y.value2; Values before exchange
y.value2 = temp; 100
} 200
int main() Values after exchange
{ 200
class_1 C1; 100
class_2 C2;
friend class
• Declare all the member functions of one class as the friend
functions of another class. In such cases, the class is called a
friend class.
• A friend class is a class whose members have access to the
private or protected members of another class
• This can be specified as follows:
class Z
{
.........
friend class X; //all member functions
of X are
//
friends to Z
#include<iostream>
using namespace std;
class A
{
int a,b;
public:
void output()
{
cout<<a<<endl<<b;
}
friend class B;
};
class B
{
int c;
public:
void ip(A &obj)
{
obj.a=23;
obj.b=24;//cin>>obj.b
}
};
main()
{
A objA;
B obj1;
obj1.ip(objA);
objA.output();

}
What is the syntax of friend
class?

A. friend classA class;


B. friend class;
C. friend classA;
D. friend class2->friend;
E. friend class ClassA
What is the syntax of friend
class?

A. friend classA class;


B. friend class;
C. friend classA;
D. friend class2->friend;
E. friend class ClassA
A friend class can access ____________________
members of other class in which it is declared as
friend.

• A. private
B. protected
C. public
D. Both A and B
A friend class can access ____________________
members of other class in which it is declared as
friend.

• A. private
B. protected
C. public
D. Both A and B
If class A is a friend of B, then B doesn’t become a
friend of A automatically.

A. TRUE
B. FALSE
C. Can be true and false
D. Can not say
If class A is a friend of B, then B doesn’t become a
friend of A automatically.

A. TRUE
B. FALSE
C. Can be true and false
D. Can not say
How many member functions in the following code?
class Box {
int capacity;
public:
void print();
friend void show();
bool compare();
friend bool lost();
};
A. 1
B. 2
C. 3
D. 4
How many member functions in the following code?
class Box {
int capacity;
public:
void print();
friend void show();
bool compare();
friend bool lost();
};
A. 1
B. 2
C. 3
D. 4

You might also like