Module 3
Module 3
Functions
Syllabus
More about Functions:
• Function overloading
• Friendly functions: friend function
• A function friendly to two classes
• Objects as function arguments
return 0;
}
Example:
Contd… #include<iostream>
using namespace std;
void add(int a, double b)
{
3. Parameters should have a different cout<<"sum = "<<(a+b);
sequence of parameters. }
void add(double a, int b)
add(int a, double b)
{
add(double a, int b)
cout<<endl<<"sum = "<<(a+b);
}
int main()
{
add(10,2.5);
add(5.5,6);
return 0;
}
How does Function Overloading work?
•Exact match:- (Function name and Parameter)
•If a not exact match is found:–
->Char, Unsigned char, and short are promoted to an int.
->Float is promoted to double
•If no match is found:
->C++ tries to find a match through the standard conversion.
•ELSE ERROR
Friend function
• 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.
• Syntax:
Characteristics of Friend function
• The function declaration should be preceded by the keyword friend.
• The function can be defined anywhere in the program like normal C++ function.
• Function definition will not use the keyword friend and scope resolution operator(: :).
• The functions that are declared with the keyword friend are known as friend function.
• A function can be declared as friend in any number of classes.
• A friend function is not a member of the class, but has rights to access private
members of the class.
Example
Program to add two complex numbers using
friend function
Contd…
• Member functions of one class can be friend function of another class. In such
cases, they are defined using the scope resolution operator as shown below:
• We can also 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. This can be
specified as follows:
Friend function of multiple classes
• In C++, we can create such functions, which are friend of more than one
class.
• If we want to make a function friend of more than one class, then the
function must be declared inside all those classes using the friend keyword.
• Such friend function must take object of all those classes as argument for
whom it is friend.
Example
Passing object as arguments
• In C++ we can pass class’s objects as arguments and also return them from a
function the same way we pass and return other variables.
• To pass an object as an argument we write the object name as the argument while
calling the function the same way we do it for other variables.
Syntax:
function_name(object_name);
Example
Output:
Returning objects
• Like normal values, function can return objects as arguments in C++.
Syntax:
object = return object_name;
Example
Output:
Constructors