SlideShare a Scribd company logo
Mrs. Pranali P. Chaudhari
Main Function
Function prototyping
Call by reference
Return by referenceReturn by reference
Inline functions
Default arguments
Const arguments
Function overloading
Friend functions and class
What is the difference between main
function in C and C++?
C does not specify the return type for theC does not specify the return type for the
main() whereas in C++ the main() returns a
value of type int.
The prototype describes the function interface to the
compiler by giving details such as the number and
type of arguments and the type of return values.
A template is used when declaring and defining aA template is used when declaring and defining a
function.
Syntax:
type function_name (argument_list);
Eg:
float volume ( int x, float y, float z)
Check whether the following function prototype
is correct or not. Give reasons.
1. float volume (int x, float y, z)
2. float volume (int, float, float)2. float volume (int, float, float)
Incorrect
Each argument variable must be declared
independently.
Correct
Variable names are optional.
C++ permits to pass parameters to the
functions by reference.
When we pass arguments by reference, the
formal arguments in the called function
become aliases to the actual arguments in
the calling function.
It is used where we would like to alter the
values of variables in the calling function.
Example:
void swap (int &a, int &b)
{
int t = a;int t = a;
a = b;
b = t;
}
Function call swap(m, n)
Values of m and n are exchanged using their
aliases a and b.
A function can also return a reference.
Example:
int & max (int & x, int & y)
{
if ( x > y )if ( x > y )
return x;
else
return y;
}
Since the return type of max() is int & the
function will return reference to x or y and not
the values.
An inline function is a function that is expanded
in line when it is invoked.
Syntax:
inline function-header
{{
function body
}
Eg:
inline double cube(double a)
{
return (a*a*a);
}
The above inline function is invoked as:
c = cube(3.0);
The speed benefits of inline functionThe speed benefits of inline function
diminish as the function grows in size.
Example
C++ allows to call a function without specifying
all its arguments.
For eg:
float amount ( float principal, int period, float
rate=0.15)
A function call:
value = amount (5000, 7); // one argument missing
value = amount ( 5000, 5, 0.12) // all arguments
In C++ an argument to a function can be
declared as const
Eg:
int strlen ( const char *p );
int length ( const string &s);
The qualifier const tells the compiler that
the function should not modify the
argument.
Function overloading means to use same
function name to create functions that
perform variety of different tasks.
The function would perform differentThe function would perform different
operations depending on the argument list in
the function call.
The correct function to be invoked is
determined by checking the number and type
of the arguments but not on the function
type.
// Declarations
int add( int a, int b); // prototype 1
int add ( int a, int b, int c); // prototype 2
double add ( double x, double y); // prototype 3
double add (int p, double q); // prototype 4double add (int p, double q); // prototype 4
double add (double p, int q); // prototype 5
//Function calls
cout << add (5, 10); // uses prototype 1
cout << add (15, 10.0); // uses prototype 4
cout << add ( 12.5, 7.5); // uses prototype 3
cout << add (5, 10, 15); // uses prototype 2
cout << add (0.75, 5); // uses prototype 5
A function call first matches the prototype having the same
number and type of arguments and then call the appropriate
function for execution.
If an exact match is not found, the compiler uses the integral
promotions to the actual arguments such as char to int, float
to double.
If either of them fails, the compiler tries to use the built in
conversations to the actual arguments and then uses the
functions whose match is unique.
long square(long n)
double square(double x)
A function call square(10) will cause an error because int
argument can be converted into either long or double there by
causing ambiguous situation.
Function overloading is used when we want
functions to perform closely related tasks.
Sometimes default arguments may be usedSometimes default arguments may be used
instead of overloading.
Example
C++ allows the common functions to be made
friendly to the classes.
For eg: consider two classes manager and
scientists and they want to use a function
income_tax().
So we make this function friendly with both the
classes, thereby allowing the function to have
access to the private data of these classes.
Declaration:
Class ABC
{
……
……
public:
……
……
friend void xyz(void); // declaration
};
The function declaration should be preceded
by the keyword friend.
A Friend function possesses certain special
characteristics:
It is not in the scope of the class to which it has been
declared as friend.
It cannot be called using the object of the class.(as it
doesn’t come under the scope of the class)
It can be invoked like a normal function without theIt 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.
It can be declared either in public or private part of
the class without affecting its meaning.
Usually, it has the objects as arguments.
Class sample
{
int a;
int b;
public:
void setvalue() { a = 25; b = 40; }
friend float mean(sample s);
};
float mean(sample s)
{
return float(s.a + s.b)/2.0;
}
int main()
{
Sample X; //Object X
X.setValue();
cout << “Mean value = “ << mean(X) << “n”;
return 0;
}
Member functions of one class can be friend
functions of another class.
class X
{
……
…………
int fun1(); // member function of X
……
};
class Y
{
……
……
friend int X :: fun1(); // fun1() of X is friend of Y
……
};
class ABC; // forward declaration
class XYZ
{
int x;
public:
void setvalue(int i ) { x = i ; }void setvalue(int i ) { x = i ; }
friend void max(XYZ, ABC);
};
class ABC
{
int a;
public:
void setvalue(int i ) { a = i; }
friend void max(XYZ, ABC);
};
void max(XYZ m, ABC n ) // definition of friend
{
if ( m.x >= n.a)
cout << m.x;
else
cout << n.a;
}}
int main()
{
ABC abc;
abc.setvalue(10);
XYZ xyz;
xyz.setvalue(20);
max(xyz, abc);
return 0;
}
A friend function can access and alter the values
of private members of the class, thus violating
the data hiding principle of OOPs.
This can be done by calling friend function byThis can be done by calling friend function by
reference.
Here the local copies of the objects are not
made instead a pointer to the address of the
object is passed and the called function directly
works on the actual object used in the call.
class class_2;
class class_1
{
int value1;
public:
void indata(int a) { value1 = a; }
void display() { cout<< value1 << “n”; }void display() { cout<< value1 << “n”; }
friend void exchange(class_1 &, class_2 &);
};
class class_2
{
int value2;
public:
void indata(int a) { value2 = a; }
void display() { cout<< value2 << “n”; }
friend void exchange(class_1 &, class_2 &);
};
void exchange(class_1 & x, class_2 & y) // object x and y are aliases
{ of C1 and C2
int temp = x.value1; // directly modifying the values of
x.value1 = y.value2; value1 and value2 of class_1 and
y.value2 = temp; class_2
}
int main()
{
class_1 c1;
class_2 c2;
c1.indata(100);c1.indata(100);
c2.indata(200);
cout << “values before exchange” << “n”;
c1.display();
c2.dispaly();
exchange( c1, c2);
cout << “values after exchange” << “n”;
c1.display();
c2.dispaly();
return 0;
}
We can declare all the member functions of
a class as a friend function of another class.
In such cases the class is known as a friend
class.
Syntax:Syntax:
class Z
{
……….
friend class X;
};
State true or false:
Class members are public by default.
Friend functions have access to only public members
of class.
An entire class can be made a friend of another class.
Functions cannot return class objects.
A function designed as private is accessible only to
member functions of that class.
A function designed as public can be accessed like any
other ordinary functions.
When will you make a function inline? Why?
When a function is small and is likely to be called many time we make it
as inline. Inline expansion makes a program run faster because the
overhead of a function call and return is eliminated.
How does an inline function differ from a pre-processor macro?
The compiler replaces the function code when the inline functions areThe compiler replaces the function code when the inline functions are
called and hence perform type checking whereas macro are simply the
substitution of code by the pre-processor before compilation and hence
no type checking or error checking.
What is the significance of an empty parenthesis in a function
declaration?
Empty parenthesis indicates that the function does not contains any
arguments.
What is the main advantages of passing arguments by
reference?
When the arguments are passed by reference then we can
alter the original data instead of its local copies.
What do you meant by overloading of a function? When doWhat do you meant by overloading of a function? When do
we use this concept?
Function overloading means to use same function name to
create functions that perform variety of different tasks.
Function overloading is used perform different operations
depending on the argument list in the function call. It is also
used for handling class objects.
Object Oriented Programming with C++ by E.
Balagurusamy.
Functions in C++

More Related Content

What's hot

Functions in c++
Functions in c++Functions in c++
Functions in c++
Maaz Hasan
 
FUNCTIONS IN C PROGRAMMING.pdf
FUNCTIONS IN C PROGRAMMING.pdfFUNCTIONS IN C PROGRAMMING.pdf
FUNCTIONS IN C PROGRAMMING.pdf
RITHIKA R S
 
Inline function
Inline functionInline function
Inline functionTech_MX
 
Function overloading and overriding
Function overloading and overridingFunction overloading and overriding
Function overloading and overriding
Rajab Ali
 
classes and objects in C++
classes and objects in C++classes and objects in C++
classes and objects in C++
HalaiHansaika
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
Nikhil Pandit
 
Function
FunctionFunction
Function
yash patel
 
Constructors in C++
Constructors in C++Constructors in C++
Constructors in C++
RubaNagarajan
 
08 c++ Operator Overloading.ppt
08 c++ Operator Overloading.ppt08 c++ Operator Overloading.ppt
08 c++ Operator Overloading.pptTareq Hasan
 
Pointers in c++
Pointers in c++Pointers in c++
Pointers in c++
Vineeta Garg
 
Function in C Programming
Function in C ProgrammingFunction in C Programming
Function in C Programming
Anil Pokhrel
 
C functions
C functionsC functions
Functions in C++
Functions in C++Functions in C++
Functions in C++
Mohammed Sikander
 
Templates in C++
Templates in C++Templates in C++
Templates in C++Tech_MX
 
Unit 7. Functions
Unit 7. FunctionsUnit 7. Functions
Unit 7. Functions
Ashim Lamichhane
 
Manipulators in c++
Manipulators in c++Manipulators in c++
Manipulators in c++
Ashok Raj
 
Function overloading ppt
Function overloading pptFunction overloading ppt
Function overloading ppt
Prof. Dr. K. Adisesha
 
Operator overloading
Operator overloadingOperator overloading
Operator overloading
Ramish Suleman
 

What's hot (20)

Functions in c++
Functions in c++Functions in c++
Functions in c++
 
Operators in C++
Operators in C++Operators in C++
Operators in C++
 
FUNCTIONS IN C PROGRAMMING.pdf
FUNCTIONS IN C PROGRAMMING.pdfFUNCTIONS IN C PROGRAMMING.pdf
FUNCTIONS IN C PROGRAMMING.pdf
 
Inline function
Inline functionInline function
Inline function
 
Function overloading and overriding
Function overloading and overridingFunction overloading and overriding
Function overloading and overriding
 
classes and objects in C++
classes and objects in C++classes and objects in C++
classes and objects in C++
 
Functions in C
Functions in CFunctions in C
Functions in C
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
 
Function
FunctionFunction
Function
 
Constructors in C++
Constructors in C++Constructors in C++
Constructors in C++
 
08 c++ Operator Overloading.ppt
08 c++ Operator Overloading.ppt08 c++ Operator Overloading.ppt
08 c++ Operator Overloading.ppt
 
Pointers in c++
Pointers in c++Pointers in c++
Pointers in c++
 
Function in C Programming
Function in C ProgrammingFunction in C Programming
Function in C Programming
 
C functions
C functionsC functions
C functions
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
 
Templates in C++
Templates in C++Templates in C++
Templates in C++
 
Unit 7. Functions
Unit 7. FunctionsUnit 7. Functions
Unit 7. Functions
 
Manipulators in c++
Manipulators in c++Manipulators in c++
Manipulators in c++
 
Function overloading ppt
Function overloading pptFunction overloading ppt
Function overloading ppt
 
Operator overloading
Operator overloadingOperator overloading
Operator overloading
 

Similar to Functions in C++

Object oriented concepts & programming (2620003)
Object oriented concepts & programming (2620003)Object oriented concepts & programming (2620003)
Object oriented concepts & programming (2620003)nirajmandaliya
 
C++ Object oriented concepts & programming
C++ Object oriented concepts & programmingC++ Object oriented concepts & programming
C++ Object oriented concepts & programming
nirajmandaliya
 
Classes function overloading
Classes function overloadingClasses function overloading
Classes function overloadingankush_kumar
 
chapter-8-function-overloading.pdf
chapter-8-function-overloading.pdfchapter-8-function-overloading.pdf
chapter-8-function-overloading.pdf
study material
 
C questions
C questionsC questions
C questions
parm112
 
Functions
FunctionsFunctions
Functions
Pragnavi Erva
 
Functions in c language
Functions in c languageFunctions in c language
Functions in c language
Tanmay Modi
 
Functions in c language
Functions in c language Functions in c language
Functions in c language
tanmaymodi4
 
Prsentation on functions
Prsentation on functionsPrsentation on functions
Prsentation on functionsAlisha Korpal
 
Functionincprogram
FunctionincprogramFunctionincprogram
Functionincprogram
Sampath Kumar
 
C function
C functionC function
C function
thirumalaikumar3
 
Unit-III.pptx
Unit-III.pptxUnit-III.pptx
Unit-III.pptx
Mehul Desai
 
New microsoft office word document (2)
New microsoft office word document (2)New microsoft office word document (2)
New microsoft office word document (2)rashmita_mishra
 
Lecture 4
Lecture 4Lecture 4
Lecture 4
Mohammed Saleh
 
PSPC-UNIT-4.pdf
PSPC-UNIT-4.pdfPSPC-UNIT-4.pdf
PSPC-UNIT-4.pdf
ArshiniGubbala3
 
Functions in c
Functions in cFunctions in c
Functions in c
kalavathisugan
 
cp Module4(1)
cp Module4(1)cp Module4(1)
cp Module4(1)
Amarjith C K
 
Functions1
Functions1Functions1
Functions1
DrUjwala1
 

Similar to Functions in C++ (20)

DS Unit 6.ppt
DS Unit 6.pptDS Unit 6.ppt
DS Unit 6.ppt
 
Object oriented concepts & programming (2620003)
Object oriented concepts & programming (2620003)Object oriented concepts & programming (2620003)
Object oriented concepts & programming (2620003)
 
C++ Object oriented concepts & programming
C++ Object oriented concepts & programmingC++ Object oriented concepts & programming
C++ Object oriented concepts & programming
 
Classes function overloading
Classes function overloadingClasses function overloading
Classes function overloading
 
chapter-8-function-overloading.pdf
chapter-8-function-overloading.pdfchapter-8-function-overloading.pdf
chapter-8-function-overloading.pdf
 
C questions
C questionsC questions
C questions
 
Functions
FunctionsFunctions
Functions
 
Functions in c language
Functions in c languageFunctions in c language
Functions in c language
 
Functions in c language
Functions in c language Functions in c language
Functions in c language
 
Prsentation on functions
Prsentation on functionsPrsentation on functions
Prsentation on functions
 
Functionincprogram
FunctionincprogramFunctionincprogram
Functionincprogram
 
C function
C functionC function
C function
 
Unit-III.pptx
Unit-III.pptxUnit-III.pptx
Unit-III.pptx
 
New microsoft office word document (2)
New microsoft office word document (2)New microsoft office word document (2)
New microsoft office word document (2)
 
Lecture 4
Lecture 4Lecture 4
Lecture 4
 
PSPC-UNIT-4.pdf
PSPC-UNIT-4.pdfPSPC-UNIT-4.pdf
PSPC-UNIT-4.pdf
 
Ch4 functions
Ch4 functionsCh4 functions
Ch4 functions
 
Functions in c
Functions in cFunctions in c
Functions in c
 
cp Module4(1)
cp Module4(1)cp Module4(1)
cp Module4(1)
 
Functions1
Functions1Functions1
Functions1
 

More from Pranali Chaudhari

Exception handling
Exception handlingException handling
Exception handling
Pranali Chaudhari
 
Files and streams
Files and streamsFiles and streams
Files and streams
Pranali Chaudhari
 
Templates
TemplatesTemplates
Managing I/O in c++
Managing I/O in c++Managing I/O in c++
Managing I/O in c++
Pranali Chaudhari
 
Inheritance
InheritanceInheritance
Inheritance
Pranali Chaudhari
 
Operator overloading
Operator overloadingOperator overloading
Operator overloading
Pranali Chaudhari
 
Constructors destructors
Constructors destructorsConstructors destructors
Constructors destructors
Pranali Chaudhari
 
Introduction to C++
Introduction to C++Introduction to C++
Introduction to C++
Pranali Chaudhari
 
Object oriented concepts
Object oriented conceptsObject oriented concepts
Object oriented concepts
Pranali Chaudhari
 

More from Pranali Chaudhari (9)

Exception handling
Exception handlingException handling
Exception handling
 
Files and streams
Files and streamsFiles and streams
Files and streams
 
Templates
TemplatesTemplates
Templates
 
Managing I/O in c++
Managing I/O in c++Managing I/O in c++
Managing I/O in c++
 
Inheritance
InheritanceInheritance
Inheritance
 
Operator overloading
Operator overloadingOperator overloading
Operator overloading
 
Constructors destructors
Constructors destructorsConstructors destructors
Constructors destructors
 
Introduction to C++
Introduction to C++Introduction to C++
Introduction to C++
 
Object oriented concepts
Object oriented conceptsObject oriented concepts
Object oriented concepts
 

Recently uploaded

Chapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptxChapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptx
Mohd Adib Abd Muin, Senior Lecturer at Universiti Utara Malaysia
 
Additional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdfAdditional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdf
joachimlavalley1
 
The approach at University of Liverpool.pptx
The approach at University of Liverpool.pptxThe approach at University of Liverpool.pptx
The approach at University of Liverpool.pptx
Jisc
 
Unit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdfUnit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdf
Thiyagu K
 
Palestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptxPalestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptx
RaedMohamed3
 
Supporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptxSupporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptx
Jisc
 
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
MysoreMuleSoftMeetup
 
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCECLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
BhavyaRajput3
 
A Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in EducationA Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in Education
Peter Windle
 
"Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe..."Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe...
SACHIN R KONDAGURI
 
Language Across the Curriculm LAC B.Ed.
Language Across the  Curriculm LAC B.Ed.Language Across the  Curriculm LAC B.Ed.
Language Across the Curriculm LAC B.Ed.
Atul Kumar Singh
 
Thesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.pptThesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.ppt
EverAndrsGuerraGuerr
 
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup   New Member Orientation and Q&A (May 2024).pdfWelcome to TechSoup   New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
TechSoup
 
Home assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdfHome assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdf
Tamralipta Mahavidyalaya
 
Embracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic ImperativeEmbracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic Imperative
Peter Windle
 
Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345
beazzy04
 
The Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdfThe Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdf
kaushalkr1407
 
Model Attribute Check Company Auto Property
Model Attribute  Check Company Auto PropertyModel Attribute  Check Company Auto Property
Model Attribute Check Company Auto Property
Celine George
 
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
Levi Shapiro
 
2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...
Sandy Millin
 

Recently uploaded (20)

Chapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptxChapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptx
 
Additional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdfAdditional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdf
 
The approach at University of Liverpool.pptx
The approach at University of Liverpool.pptxThe approach at University of Liverpool.pptx
The approach at University of Liverpool.pptx
 
Unit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdfUnit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdf
 
Palestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptxPalestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptx
 
Supporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptxSupporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptx
 
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
 
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCECLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
 
A Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in EducationA Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in Education
 
"Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe..."Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe...
 
Language Across the Curriculm LAC B.Ed.
Language Across the  Curriculm LAC B.Ed.Language Across the  Curriculm LAC B.Ed.
Language Across the Curriculm LAC B.Ed.
 
Thesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.pptThesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.ppt
 
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup   New Member Orientation and Q&A (May 2024).pdfWelcome to TechSoup   New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
 
Home assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdfHome assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdf
 
Embracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic ImperativeEmbracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic Imperative
 
Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345
 
The Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdfThe Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdf
 
Model Attribute Check Company Auto Property
Model Attribute  Check Company Auto PropertyModel Attribute  Check Company Auto Property
Model Attribute Check Company Auto Property
 
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
 
2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...
 

Functions in C++

  • 1. Mrs. Pranali P. Chaudhari
  • 2. Main Function Function prototyping Call by reference Return by referenceReturn by reference Inline functions Default arguments Const arguments Function overloading Friend functions and class
  • 3. What is the difference between main function in C and C++? C does not specify the return type for theC does not specify the return type for the main() whereas in C++ the main() returns a value of type int.
  • 4. The prototype describes the function interface to the compiler by giving details such as the number and type of arguments and the type of return values. A template is used when declaring and defining aA template is used when declaring and defining a function. Syntax: type function_name (argument_list); Eg: float volume ( int x, float y, float z)
  • 5. Check whether the following function prototype is correct or not. Give reasons. 1. float volume (int x, float y, z) 2. float volume (int, float, float)2. float volume (int, float, float) Incorrect Each argument variable must be declared independently. Correct Variable names are optional.
  • 6. C++ permits to pass parameters to the functions by reference. When we pass arguments by reference, the formal arguments in the called function become aliases to the actual arguments in the calling function. It is used where we would like to alter the values of variables in the calling function.
  • 7. Example: void swap (int &a, int &b) { int t = a;int t = a; a = b; b = t; } Function call swap(m, n) Values of m and n are exchanged using their aliases a and b.
  • 8. A function can also return a reference. Example: int & max (int & x, int & y) { if ( x > y )if ( x > y ) return x; else return y; } Since the return type of max() is int & the function will return reference to x or y and not the values.
  • 9. An inline function is a function that is expanded in line when it is invoked. Syntax: inline function-header {{ function body } Eg: inline double cube(double a) { return (a*a*a); }
  • 10. The above inline function is invoked as: c = cube(3.0); The speed benefits of inline functionThe speed benefits of inline function diminish as the function grows in size. Example
  • 11. C++ allows to call a function without specifying all its arguments. For eg: float amount ( float principal, int period, float rate=0.15) A function call: value = amount (5000, 7); // one argument missing value = amount ( 5000, 5, 0.12) // all arguments
  • 12. In C++ an argument to a function can be declared as const Eg: int strlen ( const char *p ); int length ( const string &s); The qualifier const tells the compiler that the function should not modify the argument.
  • 13. Function overloading means to use same function name to create functions that perform variety of different tasks. The function would perform differentThe function would perform different operations depending on the argument list in the function call. The correct function to be invoked is determined by checking the number and type of the arguments but not on the function type.
  • 14. // Declarations int add( int a, int b); // prototype 1 int add ( int a, int b, int c); // prototype 2 double add ( double x, double y); // prototype 3 double add (int p, double q); // prototype 4double add (int p, double q); // prototype 4 double add (double p, int q); // prototype 5 //Function calls cout << add (5, 10); // uses prototype 1 cout << add (15, 10.0); // uses prototype 4 cout << add ( 12.5, 7.5); // uses prototype 3 cout << add (5, 10, 15); // uses prototype 2 cout << add (0.75, 5); // uses prototype 5
  • 15. A function call first matches the prototype having the same number and type of arguments and then call the appropriate function for execution. If an exact match is not found, the compiler uses the integral promotions to the actual arguments such as char to int, float to double. If either of them fails, the compiler tries to use the built in conversations to the actual arguments and then uses the functions whose match is unique. long square(long n) double square(double x) A function call square(10) will cause an error because int argument can be converted into either long or double there by causing ambiguous situation.
  • 16. Function overloading is used when we want functions to perform closely related tasks. Sometimes default arguments may be usedSometimes default arguments may be used instead of overloading. Example
  • 17. C++ allows the common functions to be made friendly to the classes. For eg: consider two classes manager and scientists and they want to use a function income_tax(). So we make this function friendly with both the classes, thereby allowing the function to have access to the private data of these classes.
  • 18. Declaration: Class ABC { …… …… public: …… …… friend void xyz(void); // declaration }; The function declaration should be preceded by the keyword friend.
  • 19. A Friend function possesses certain special characteristics: It is not in the scope of the class to which it has been declared as friend. It cannot be called using the object of the class.(as it doesn’t come under the scope of the class) It can be invoked like a normal function without theIt 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. It can be declared either in public or private part of the class without affecting its meaning. Usually, it has the objects as arguments.
  • 20. Class sample { int a; int b; public: void setvalue() { a = 25; b = 40; } friend float mean(sample s); }; float mean(sample s) { return float(s.a + s.b)/2.0; } int main() { Sample X; //Object X X.setValue(); cout << “Mean value = “ << mean(X) << “n”; return 0; }
  • 21. Member functions of one class can be friend functions of another class. class X { …… ………… int fun1(); // member function of X …… }; class Y { …… …… friend int X :: fun1(); // fun1() of X is friend of Y …… };
  • 22. class ABC; // forward declaration class XYZ { int x; public: void setvalue(int i ) { x = i ; }void setvalue(int i ) { x = i ; } friend void max(XYZ, ABC); }; class ABC { int a; public: void setvalue(int i ) { a = i; } friend void max(XYZ, ABC); };
  • 23. void max(XYZ m, ABC n ) // definition of friend { if ( m.x >= n.a) cout << m.x; else cout << n.a; }} int main() { ABC abc; abc.setvalue(10); XYZ xyz; xyz.setvalue(20); max(xyz, abc); return 0; }
  • 24. A friend function can access and alter the values of private members of the class, thus violating the data hiding principle of OOPs. This can be done by calling friend function byThis can be done by calling friend function by reference. Here the local copies of the objects are not made instead a pointer to the address of the object is passed and the called function directly works on the actual object used in the call.
  • 25. class class_2; class class_1 { int value1; public: void indata(int a) { value1 = a; } void display() { cout<< value1 << “n”; }void display() { cout<< value1 << “n”; } friend void exchange(class_1 &, class_2 &); }; class class_2 { int value2; public: void indata(int a) { value2 = a; } void display() { cout<< value2 << “n”; } friend void exchange(class_1 &, class_2 &); };
  • 26. void exchange(class_1 & x, class_2 & y) // object x and y are aliases { of C1 and C2 int temp = x.value1; // directly modifying the values of x.value1 = y.value2; value1 and value2 of class_1 and y.value2 = temp; class_2 } int main() { class_1 c1; class_2 c2; c1.indata(100);c1.indata(100); c2.indata(200); cout << “values before exchange” << “n”; c1.display(); c2.dispaly(); exchange( c1, c2); cout << “values after exchange” << “n”; c1.display(); c2.dispaly(); return 0; }
  • 27. We can declare all the member functions of a class as a friend function of another class. In such cases the class is known as a friend class. Syntax:Syntax: class Z { ………. friend class X; };
  • 28. State true or false: Class members are public by default. Friend functions have access to only public members of class. An entire class can be made a friend of another class. Functions cannot return class objects. A function designed as private is accessible only to member functions of that class. A function designed as public can be accessed like any other ordinary functions.
  • 29. When will you make a function inline? Why? When a function is small and is likely to be called many time we make it as inline. Inline expansion makes a program run faster because the overhead of a function call and return is eliminated. How does an inline function differ from a pre-processor macro? The compiler replaces the function code when the inline functions areThe compiler replaces the function code when the inline functions are called and hence perform type checking whereas macro are simply the substitution of code by the pre-processor before compilation and hence no type checking or error checking. What is the significance of an empty parenthesis in a function declaration? Empty parenthesis indicates that the function does not contains any arguments.
  • 30. What is the main advantages of passing arguments by reference? When the arguments are passed by reference then we can alter the original data instead of its local copies. What do you meant by overloading of a function? When doWhat do you meant by overloading of a function? When do we use this concept? Function overloading means to use same function name to create functions that perform variety of different tasks. Function overloading is used perform different operations depending on the argument list in the function call. It is also used for handling class objects.
  • 31. Object Oriented Programming with C++ by E. Balagurusamy.