CM3104
UNIT 3. Functions In C++
3.1 Introduction: The main function, function prototype, call by reference,
return by reference, inline functions, default arguments, const arguments
3.2 More on function: Function overloading, friend functions, virtual functions,
pure virtual functions, inline functions, making outside function inline,
nesting of member functions, private member functions, static member
functions, object as a function argument, returning an object.
3.3 String functions: Introduction, library string functions, creating string
objects, manipulating string objects, string characteristics, accessing
characters in strings, user
****************************************************************
The Main function
→ The main function is the starting point for the execution of the program.
→ Definition of the main function:
→ In C++, the main ( ) function returns a value of type intto the operating
system.
→ Prototype of the main( ) function
int main( );
→ The functions that have a return value should use the return statement for
termination.
int main( ){
---------
return 0; }
→ If we doesn’t specifies the return type of the main ( ) function then C++
takes by default the return type as integer.
Function Prototype
→ A function prototype tells the compiler
• Name of the function,
• Type of data returned by the function (Return type),
• Number of parameters,
1|Page 186_SHRADDHA KESHAO BONDE_N2
CM3104
• Types of the parameters, and
• Order in which these parameters are expected.
→ The compiler use function prototypes to validate function calls.
→ Syntax: Return-type function-name(parameters);
→ Example: int maximum(int, int);
→ Here, return type is integer, function name is maximum, no of arguments
are 2 of type integer.
→ int sum(int x, int y);
→ In the function prototype, all the argument variable must be declared
independently inside the parenthesis.
→ In the function declaration, the names of the arguments are dummy
variables and therefore they are optional.
→ Example:
int sum(int a, int b){
int total=a+b;
......
......
}
Call by Reference (Passing by reference)
→ When a function is called using the Reference variable then it is known as
Call by Reference method.
→ Reference variable creates alias for variables.
→ So no waste of memory.
→ Example:
void swap(int ,int ) // function declaration
swap(a, b); // function call
void swap(int &x,int &y) // function definition use Reference variable{
int temp; temp = x;
x =y;
y = temp;
}
→ Here, variable x &y are reference variable of variable a & b
2|Page 186_SHRADDHA KESHAO BONDE_N2
CM3104
Return by Reference
→ A function can also return a reference.
→ Example:
int & max(int & , int &);
void main(){
int a=10, b=20,m; m = max(a, b);
cout<<”Maximum nos:”<<m;
}
int & swap (int &x, int &y){
if( x > y ) return x;
else return y;
}
→ Here, function returns reference to x or y (not value) and return type is
int&.
Inline Function
→ The functions can be made inline by adding KEYWORD inline to the
function definition.
→ An inline function is a function that is expanded in line when it is
invoked.
→ The complier replaces the function call with the function code.
→ Inline function saves time of calling function, saving registers etc.
→ If function has very few lines of code and simple expressions then only it
should be used as inline otherwise behave as normal function.
→ For ex- Some Critical Situations
→ If a loop, a switch , goto exists in function body, If function is not
returning any value
→ If function contains static variables.
→ If it is recursive.
→ Then function does not work as inline.
→ Example:
inline int cube(int n){ return n*n*n; }
int main(){ int c; c = cube(10); cout<<c; }
→ Function call is replaced with expression So,
c = cube(10);
→ Becomes c =10*10*10; at compile time.
3|Page 186_SHRADDHA KESHAO BONDE_N2
CM3104
→ C++ provides a mechanism called inline function . When a function is
declared as inline the compiler copies the code of the function in calling
function i.e function body is inserted in place of function call during
compilation.
→ Passing of control between coller and collee function is avoided.
→ Program - Write a program to find square of a number.
#include <iostream.h>
inline float square(float j){ return(j*j); }
void main()
{ int p, q;
cout<<”enter a number:” ; cin>>p;
q=square(p);
cout<<q;
}
Making outside function Inline
→ One of the objectives of OOP is to separate the details of implementation
from the class definition. It is therefore good practice to define the
member functions outside the class.
→ We can define a member function outside the class definition and still
make it inline by just using the qualifier inline in the header line of the
function definition.
→ Example:
class item{
...... public:
void getdata(int a,float b);
};
inline void item :: getdata(int a,float b){
number=a;
cost=b;
}
Default Arguments
→ Default values are specified when the function is declared
→ We must add default arguments from right to left.
→ We cannot provide a default value to a particular argument in the middle
of an argument list.
4|Page 186_SHRADDHA KESHAO BONDE_N2
CM3104
→ Default arguments are useful in situations where some arguments always
have the same value.
→ C++ compiler allows the programmer to assign default values in function
prototype.
→ When the function is called with less parameter or without parameter the
default values are used for operation.
Constant Arguments or Const Arguments
→ In C++ ,an argument to a function can be declared as constant using
keyword const.
→ Syntax: const datatype variable_name;
→ Example1: int square(const int a);
float area(const float r);
→ In above statement, the const keyword tells the complier that the function
should not modify the argument.
→ Example2: [Write any one example]
int fun(const int x){ int x=y;
x=x+1; //Invalid
y=x; //valid
return (y); }
→ Const argument cannot modify.
Function Overloading
→ Overloading means to use the same thing for different purpose C++
allows overloading of functions.
→ Definition: “When multiple functions with same name are used for
different task and purpose it is known as function overloading”.
→ The overloading function must be different in its argument list & with
different data type
→ Compiler Differentiate it by,
• Different no of arguments
• Different types of arguments
• Different return type
→ Example: Area of shape is defined as
float area(float r); //area of circle
float area(float l, float b); //area of rectangle
5|Page 186_SHRADDHA KESHAO BONDE_N2
CM3104
Friend Function
→ A friend function is a function that is not a member of a class but it can
access private and protected member of the class in which it is declared
as friend.
→ Since friend function is not a member of class it cannot be accessed using
object of the class.
→ Sometimes it is required that private
→ A function can be declared as a friend by preceding function declaration
with friend keyword as shown below:
friend Return_Type Function_Name (Argument List);
→ Eg: Friend void add();
→ Friend function can be called as follows
function_name(actual arguments);
→ The function that is declared with the keyword friend is known as friend
function
→ This function can be defined else where in the program.
→ The function definition does not use either keyword friend or the scope
operator::
→ A function can be declared as a friend in any number of classes.
→ A friend function although not a member function, has full access right to
the private members of the class
→ Friend function having following characteristics:
(1) A friend function can be declared inside class but it is not member of
the class.
(2) It can be declared either public or private without affecting its
meaning.
(3) A friend function is not a member of class so it is not called using
object of the class. It is called like normal external function.
(4) A friend function accepts object as an argument to access private or
public member of the class.
(5) A friend function can be declared as friend in any number of classes.
Nesting of Member function
→ A member function can be called by using its name inside another
member function of the same class. This is known as nesting of member
functions.
→ Example:
class student{
6|Page 186_SHRADDHA KESHAO BONDE_N2
CM3104
------- public:
void putdata(){
------- totalmarks();
}
void totalmarks(){ ------- }
};
Private Member function
→ Normally we define data members as private and function member as
public.
→ But in some cases, we require to declare function as private.
→ A function declared inside the class's private section is known as "private
member function". A private member function is accessible through the
only public member function inside the same class only.
→ Even an object cannot invoke a private function using the dot operator.
Static Member function
→ Like a static member variable we can also have static member function.
→ A member function declared with static keyword is called as static
member function.
→ Static member function has following characteristics/properties
→ Static function can have access to only other static members/functions
declared in same class
→ Static member function can be called using class name(instead of object)
as
Class_name:: function_name;
→ Static member function cannot be Virtual.
→ They cannot be declared as constant or volatile.
→ A Static member function does not have this pointer.
→ There cannot be static and non-static version of the same function
→ Static member function can be invoked using class name, not object.
String Functions
→ String literals such as “Hello, world!” are actually represented by C++ as
a sequence of characters in memory. In other words, a string is simply a
7|Page 186_SHRADDHA KESHAO BONDE_N2
CM3104
character array and can be manipulated as such. Consider the following
program:
→ #include <iostream>
using namespace std;
int main() {
char helloworld[] = {'H', 'e', 'l', 'l', 'o', ',', ' ', 'w', 'o', 'r', 'l', 'd', '!', '\0' };cout
<< helloworld <<endl;
return 0; }
→ This program prints Hello, world! Note that the character array
helloworld ends with a special character known as the null character. This
character is used to indicate the end of the string.
→ Character arrays can also be initialized using string literals. In this case,
no null character is needed, as the compiler will automatically insert one:
char helloworld[] = “Hello, world!”;
→ The individual characters in a string can be manipulated either directly by
the programmer or by using special functions provided by the C/C++
libraries. These can be included in a program through the use of the
#include directive. Of particular note are the following:
• cctype (ctype.h): character handling
• cstdio (stdio.h): input/output operations
• cstdlib (stdlib.h): general utilities
• cstring (string.h): string manipulation
→ Standard Template Library- algorithm.h: The header <algorithm> defines
a collection of functions especially designed to be used on ranges of
elements.
Library String Functions
C++ supports a wide range of functions that manipulate null-terminated strings:
1. strcpy(s1, s2); - Copies string s2 into string s1.
2. strcat(s1, s2); - Concatenates string s2 onto the end of
string s1.
3. strlen(s1); -Returns the length of string s1.
4. strcmp(s1, s2); -Returns 0 if s1 and s2 are the same; less
than 0 if s1<s2; greater than 0 if s1>s2.
8|Page 186_SHRADDHA KESHAO BONDE_N2
CM3104
5. strchr(s1, ch); -Returns a pointer to the first occurrence of character ch in
string s1.
6. strstr(s1, s2); -Returns a pointer to the first occurrence of string s2 in string
s1.
Creating String Object
→ C++ also provides it’s own string class. So you can create string object.
→ This class is provided by the standard C++ library.
→ Unlike character array from C, the C++ string does not have a fixed
length.
→ For example, the code below, reads and prints the
user’s name but without knowing the size of the name:int main () {
// size is not needed
string name;
cout << "What is your name: ";
cin >> name;
cout << "Welcome " << name << endl; }
String Manipulation With C++ String Class
→ Concatenation – Combines two string into one. Simply use the + operator.
See example below
→ String length – Use length( ) method
→ Searching strings – Accessing a character within a string. Use the find( )
method
→ Substrings – Returning part of a string. Use the substr()method.
→ Replacing – Replacing part of a string. Use the replace() method
→ Insertion – Inserting character(s) into a string. Using the insert() method
→ Erase – Removing part of a string. Use the erase() method.
String Characteristics
→ C++ also provides it’s own string class
→ A string header <string> needs to be included in the program to use the
string class.
9|Page 186_SHRADDHA KESHAO BONDE_N2
CM3104
→ In C++, string is an object of std::string class that represents sequence of
characters or we can use using namespace std;
→ A string is made up of a sequence of characters, such as letters, digits,
symbols, or spaces.
→ Strings are usually indicated by single or double quotation marks, for
example, “Welcome“,”Programming”.
→ A sequence of characters can be represented using an object of a class in
C++.
→ We can perform many operations on strings such as concatenation,
comparison, conversion etc.
Accessing Characters in Strings
→ String class stores the characters as a sequence of bytes with the
functionality of allowing access to the single-byte character.
→ There are several ways to access substrings and individual characters of a
string.
→ The string class supports the following functions for this purpose:
→ operator[] - returns the reference to the character at the position specified
as the argument ex. str[2].
→ at()- function is used for accessing individual characters. With this
function, character by character can be accessed from the given string.
→ substr()- function is used for retrieving a substring from a given string.
This function takes two values start & len
• string.h is the header file required for string functions.
• The starting index is 0.
• Syntax- string substr (size_type start, size_type len);
→ find()- function is used to find the first occurrence of a substring in the
specified string being called upon.
• It returns the index of the first occurrence of the substring in the string.
• The default value of the starting position is 0.
• If the substring is not found then the function returns -1
• Syntax- int find (const string& str);
→ find_first_of()- function is used to find the first character that matches
any of the characters specified in the arguments. This function takes two
arguments str and pos.
Ex- cout << s.find_first_of(‘P’);
10 | P a g e 186_SHRADDHA KESHAO BONDE_N2
CM3104
→ find_last_of()- function is used for finding the location of last occurrence
of the specified characters from the given string.
Ex- cout << s.find_last_of('m');
********************************************************
11 | P a g e 186_SHRADDHA KESHAO BONDE_N2