Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
SlideShare a Scribd company logo
Functions in C++
Objectives
In this chapter you will learn about
•Strict type checking
•Function Overloading
•Default Arguments
•Inline Function
• In C, Prototype is not required if the function
returns integer.
• printf can be used without including stdio.h
 In C++, prototype is compulsory even if functions
return int.
 Inclusion of stdio.h is compulsory if you are using printf
function.
C PROGRAM C PROGRAM
• Can we pass argument for function given the
following Prototype
• int func();
• In C –Yes , says that a function can take zero or more
number of arguments. (K & R Style of Prototyping)
• In C++ - No, says that a function takes zero arguments
 A feature of C++ which allows multiple functions to
have same function name
 Calls to an overloaded function are resolved using
function signatures.
 Allows multiple functions which perform similar tasks
to be grouped under a single name “single interface
and multiple implementations”
Functions in C++
 How does C++ compiler distinguishes
between different functions when it
generates object code
 It changes names by adding information
about arguments. 
 This technique of adding additional
information to function names is
called Name Mangling
Functions in C++
 What is the difference between strcpy
and strncpy?
 Write two functions by name mystrcpy.
• First functions takes two arguments (dest , src)
• Second takes three arguments(dest,src,n);
Functions in C++
 “Single interface multiple implementations” is
technically termed as “Polymorphism”.
 The binding takes place during compile time, so its
called “compile time polymorphism” or “static
polymorphism”.
 Ensure that function overloading in unambiguous
Functions in C++
int main( )
{
char str[50];
cout <<"Enter a name : ";
cin >> str;
cout <<"Entered name is " << str;
}
.getline(str , 50 );; .getline(str , 50 , ‘.’ );
• A default argument is a value provided in function declaration
that is automatically assigned by the compiler if caller of the
function doesn't provide a value for the argument.
• Allows a function to be called without providing one or more
trailing arguments.
• Default arguments should be provided only in function prototype
and shouldn’t be repeated in function definition.The compiler
uses the prototype to build a function call and not the function
definition.
• Only trailing arguments should be given default values. i.e., you
cant have a default argument followed by a non default argument.
void printBinary(int num,int bits = 8);
int main( )
{
printBinary(23);
printBinary(500 , 16);
printBinary(28 );
}
void printBinary(int num,int bits)
{
for(int i = bits - 1 ; i >= 0 ; i--)
cout << ((num & 1 << i )?1:0) ;
}
Functions in C++
Functions in C++
 If a function is declared as inline, at the time of
compilation, the body of the function is expanded at the
point at which it is invoked.
 For small functions, the inline function removes all the
overheads of function calls.
 To make a function inline prefix the keyword inline
before the function name Syntax is
 inline <return_Type> <Func_Name>(arguments)
 Not all requests to make a function inline are honored.
Generally C++ examines the
• complexity of the function
• should request for inline replacement only if the functions are short.
 The compiler may ignore the function as inline when:
• If there are loops, switch statements or goto’s in the function
• If there are static variables in a function
• If the function is recursive
• If the function call and function definition are not in a single translation
unit
 Inline functions are functionally similar to #define
macros. In both the cases, the body of the macro or the
function is expanded. But inline functions are preferred
over macros because of three main reasons:
• Argument Evaluation - Arguments are first evaluated and then
expanded unlike in macros where arguments are expanded and then
evaluated.
• Type Checking - The types of the arguments are checked against the
parameter list in the declaration for the function. As a result, any
mismatch in the parameters can be detected at the time of
compilation.
• Overloading - inline functions can be overloaded, which is not
possible in the case of macros.
Functions in C++
Functions in C++
#define square(x) x * x
OR
inline int square(int x)
{
return x * x;
}
int main( )
{
int x = 5;
cout << square( x + 2) << endl;
return 0;
}
Functions in C++
• Prototypes are a must in C++
• Every function should have a explicit return-type.
• Multiple functions can have same name with
different signature.
• Default parameters allows us to pass lesser
arguments to functions.
• Default parameters will help in combining multiple
functions into one.
• Inline functions to be used as alternative to macros
• Reference is an alternate name given to existing
variable
Functions in C++

More Related Content

Functions in C++

  • 2. Objectives In this chapter you will learn about •Strict type checking •Function Overloading •Default Arguments •Inline Function
  • 3. • In C, Prototype is not required if the function returns integer. • printf can be used without including stdio.h
  • 4.  In C++, prototype is compulsory even if functions return int.  Inclusion of stdio.h is compulsory if you are using printf function.
  • 5. C PROGRAM C PROGRAM
  • 6. • Can we pass argument for function given the following Prototype • int func(); • In C –Yes , says that a function can take zero or more number of arguments. (K & R Style of Prototyping) • In C++ - No, says that a function takes zero arguments
  • 7.  A feature of C++ which allows multiple functions to have same function name  Calls to an overloaded function are resolved using function signatures.  Allows multiple functions which perform similar tasks to be grouped under a single name “single interface and multiple implementations”
  • 9.  How does C++ compiler distinguishes between different functions when it generates object code  It changes names by adding information about arguments.   This technique of adding additional information to function names is called Name Mangling
  • 11.  What is the difference between strcpy and strncpy?  Write two functions by name mystrcpy. • First functions takes two arguments (dest , src) • Second takes three arguments(dest,src,n);
  • 13.  “Single interface multiple implementations” is technically termed as “Polymorphism”.  The binding takes place during compile time, so its called “compile time polymorphism” or “static polymorphism”.  Ensure that function overloading in unambiguous
  • 15. int main( ) { char str[50]; cout <<"Enter a name : "; cin >> str; cout <<"Entered name is " << str; } .getline(str , 50 );; .getline(str , 50 , ‘.’ );
  • 16. • A default argument is a value provided in function declaration that is automatically assigned by the compiler if caller of the function doesn't provide a value for the argument. • Allows a function to be called without providing one or more trailing arguments.
  • 17. • Default arguments should be provided only in function prototype and shouldn’t be repeated in function definition.The compiler uses the prototype to build a function call and not the function definition. • Only trailing arguments should be given default values. i.e., you cant have a default argument followed by a non default argument.
  • 18. void printBinary(int num,int bits = 8); int main( ) { printBinary(23); printBinary(500 , 16); printBinary(28 ); } void printBinary(int num,int bits) { for(int i = bits - 1 ; i >= 0 ; i--) cout << ((num & 1 << i )?1:0) ; }
  • 21.  If a function is declared as inline, at the time of compilation, the body of the function is expanded at the point at which it is invoked.  For small functions, the inline function removes all the overheads of function calls.  To make a function inline prefix the keyword inline before the function name Syntax is  inline <return_Type> <Func_Name>(arguments)
  • 22.  Not all requests to make a function inline are honored. Generally C++ examines the • complexity of the function • should request for inline replacement only if the functions are short.  The compiler may ignore the function as inline when: • If there are loops, switch statements or goto’s in the function • If there are static variables in a function • If the function is recursive • If the function call and function definition are not in a single translation unit
  • 23.  Inline functions are functionally similar to #define macros. In both the cases, the body of the macro or the function is expanded. But inline functions are preferred over macros because of three main reasons: • Argument Evaluation - Arguments are first evaluated and then expanded unlike in macros where arguments are expanded and then evaluated. • Type Checking - The types of the arguments are checked against the parameter list in the declaration for the function. As a result, any mismatch in the parameters can be detected at the time of compilation. • Overloading - inline functions can be overloaded, which is not possible in the case of macros.
  • 26. #define square(x) x * x OR inline int square(int x) { return x * x; } int main( ) { int x = 5; cout << square( x + 2) << endl; return 0; }
  • 28. • Prototypes are a must in C++ • Every function should have a explicit return-type. • Multiple functions can have same name with different signature. • Default parameters allows us to pass lesser arguments to functions. • Default parameters will help in combining multiple functions into one. • Inline functions to be used as alternative to macros • Reference is an alternate name given to existing variable

Editor's Notes

  1. (No assumption that a function returns int if no prototype is mentioned as in C) int main() { int result = add(5 , 8); printf(&amp;quot; %d&amp;quot; , result); } int add(int a,int b) { return a + b; } Change the extension to c++ and compile the program
  2. http://stackoverflow.com/questions/3092006/function-declaration-kr-vs-ansi In C, A non void function can skip the return statement(No compilation error, returns some garbage)
  3. OVERLOADING A FUNCTION NAME If you have two or more function definitions for the same function name, that is called overloading. When you overload a function name, the function definitions must have different numbers of formal parameters or some formal parameters of different types. When there is a function call, the compiler uses the function definition whose number of formal parameters and types of formal parameters match the arguments in the function call. (Interface always refers to “function names” and implementation always refers to “data and function definition”). A best match must be unique. Function selection involves the following steps. The compiler first tries to find an exact match in which the types of actual arguments are the same and use that function. If an exact match is not found, the compiler uses the integral promotions to actual arguments, such as, char to int, or float to double to find the match. In case of multiple matches the compiler will generate an error message.
  4. #include &amp;lt;iostream&amp;gt; using namespace std; double area(int radius) { return 3.14 * radius * radius; } int area(int length,int breadth) { return length * breadth; } int main() { cout &amp;lt;&amp;lt; area(5) &amp;lt;&amp;lt; endl; cout &amp;lt;&amp;lt; area(5 , 3) &amp;lt;&amp;lt; endl; }
  5. C++ supports function overloading, i.e., there can be more than one functions with same name and differences in parameters. How does C++ compiler distinguishes between different functions when it generates object code – it changes names by adding information about arguments. This technique of adding additional information to function names is called Name Mangling
  6. #include &amp;lt;iostream&amp;gt; using namespace std; void mystrcpy(char *dest,const char *src) { while((*dest = *src)) { dest++; src++; } } void mystrcpy(char *dest,const char *src,int n) { for(int i = 0 ; i &amp;lt; n &amp;&amp; (*dest = *src) ; i++) { dest++; src++; } } int main() { char src[20] = &amp;quot;SIKANDER&amp;quot;; char dest1[20] = &amp;quot;&amp;quot;; char dest2[20] = &amp;quot;&amp;quot;; mystrcpy(dest1 , src); mystrcpy(dest2 , src , 3); cout &amp;lt;&amp;lt;&amp;quot;Dest 1 = &amp;quot; &amp;lt;&amp;lt; dest1 &amp;lt;&amp;lt; endl; cout &amp;lt;&amp;lt;&amp;quot;Dest 2 = &amp;quot; &amp;lt;&amp;lt; dest2 &amp;lt;&amp;lt; endl; }
  7. default_printbinary.cpp
  8. #include &amp;lt;iostream&amp;gt; #include &amp;lt;cstdio&amp;gt; using namespace std; void myprint(const char *str) { printf(str); } void myprint(const char *str,FILE *fp) { fprintf(fp , str); } int main( ){ myprint(&amp;quot;HELLO WORLD&amp;quot;); //Print to Monitor FILE *fp = fopen(&amp;quot;myfile.txt&amp;quot; , &amp;quot;w&amp;quot;); myprint(&amp;quot;WELCOME TO BANGALORE&amp;quot; , fp); //Print to file }
  9. #include &amp;lt;iostream&amp;gt; #include &amp;lt;cstdio&amp;gt; using namespace std; void myprint(const char *str,FILE *fp = stdout) { fprintf(fp , str); } int main( ){ myprint(&amp;quot;HELLO WORLD&amp;quot;); //Print to Monitor FILE *fp = fopen(&amp;quot;myfile.txt&amp;quot; , &amp;quot;w&amp;quot;); myprint(&amp;quot;WELCOME TO BANGALORE&amp;quot; , fp); //Print to file }
  10. Inlinefunc_macro.cpp
  11. Inline functions have internal linkage, can be placed in header files