C++ 2
C++ 2
2.1 Functions
In C++, a function is a group of statements that is given a name, and which can be
called from some point of the program.
Advantages:
• Reusability:
A function once written can be invoked again and again, thus helping us to
reuse the code and removing data redundancy.
• Modularity:
Functions can help us in breaking a large, hard to manage problem into
smaller manageable sub-problems.
• Reduced Program Size:
Functions can reduce the size of the program by removing data
redundancy.
• Easy Debugging:
Using functions, debugging of a program becomes very easy, as it is
easier to locate and rectify the bug in the program if functions are used.
• Easy Updating:
If we need to update some code in the program, then it is much more easier in case we
have used functions, as the changes need to be made in one place only (in function).
A.PRAKASH (GL),PG & RESEARCH DEPARTMENT OF COMPUTER SCIENCE , ARIGNAR ANNA GOVERNMENT ARTS
COLLEGE , CHEYYAR-604 407 Page 1
C++ functions are classified in two categories. They are
The library functions can be used in any program by including respective header files.
The header files must be included using #include pre-processor directive. For example, a
mathematical function uses math.h header file. The programmer can also define and use his/her
own functions for performing some specific tasks. Such functions are called user-defined
functions.
A.PRAKASH (GL),PG & RESEARCH DEPARTMENT OF COMPUTER SCIENCE , ARIGNAR ANNA GOVERNMENT ARTS
COLLEGE , CHEYYAR-604 407 Page 2
void show (void);
float sum (float, int);
float sum (float x, int y);
2. Function Call:
A function must be called by its name followed by argument, or without argument,
list enclosed in parenthesis and terminated by semicolon.
Syntax of function call is as follows:
function-name(with/without argument list);
In the above statement, function-name is the name of the function, arguments are
within the bracket and arguments are separated by comma. If arguments are absent one
can write void within the bracket.
3. Function Definition:
The first line is called function definition and function body follows it. The function
definition and function prototype should match with each other. The function body is
enclosed within curly braces. The function can be defined anywhere. If the function is
defined before its caller, then its prototype declaration is optional.
Syntax of function call is as follows:
return_data_type function-name(argument/parameter list);
{
variable declarations
function statements
}
4. Actual and Formal Argument:
The arguments declared in caller function and given in the function call are called
actual arguments.The arguments declared in the function definition are known as formal
arguments.
5. The return Statement:
The return statement is used to return value to the caller function. The return statement
returns only one value at a time. When a return statement is encountered , complier
transfers the control of the program to caller function.
The syntax of return statement is as follows:
return (variable name); or
return variable name;
A.PRAKASH (GL),PG & RESEARCH DEPARTMENT OF COMPUTER SCIENCE , ARIGNAR ANNA GOVERNMENT ARTS
COLLEGE , CHEYYAR-604 407 Page 3
There are three methods:
In this type, values of actual arguments are passed to the formal arguments and
operation is done on the formal arguments. Any change in the formal arguments does not effect
to the actual arguments because formal arguments are photocopy of actual arguments. Changes
made in the formal arguments are local to the block of called function. Once control returns back
to the calling function, the changes made will vanish.
int main()
{
int x,y;
cout<<“\n Enter Values of X & Y:”;
cin>>x>>y;
cout<<“\n\n In function main() before swap()”;
cout<<“\n Values X=”<<x <<“ and Y= ”<<y;
swap(x,y);
cout<<“\n\n In function main() after swap() ”;
cout<<“\n Values X=”<<x <<“ and Y= ”<<y;
return 0;
}
void swap(int a, int b)
{
int k;
k=a;
a=b;
b=k;
cout<<“\n In function swap() ”;
cout<<“\n Values X=”<<a <<“ and Y= ”<<b;
}
A.PRAKASH (GL),PG & RESEARCH DEPARTMENT OF COMPUTER SCIENCE , ARIGNAR ANNA GOVERNMENT ARTS
COLLEGE , CHEYYAR-604 407 Page 4
Output:
Enter Values of X & Y :5 4
In function main() before swap() Values X=5 and Y= 4
In function swap() Values X=4 and Y= 5
In function main() after swap() Values X=5 and Y= 4
Call by Address:
In this type, instead of passing values, addresses of actual parameters are
passed to the function by using pointers. Function operates on addresses rather than values. Here
the formal arguments are pointers to the actual arguments. Because of this, when the values of
formal arguments are changed, the values of actual parameters also change. Hence changes made
in the argument are permanent. The following example illustrates passing the arguments to the
function using call by address method.
#include<iostream>
using namespace std;
void swap (int *, int *);
int main()
{
int x,y;
cout<<“\n Enter Values of X & Y:”;
cin>>x>>y;
swap(&x,&y);
cout<<“\n In main() Values X=”<<x <<“ and Y=”<<y;
return 0;
}
void swap(int *a, int *b)
{
int *k;
*k=*a;
*a=*b;
*b=*k;
cout<<“\n In swap() Values X=”<<*a <<“ and Y=”<<*b;
}
OUTPUT
Enter Values of X & Y :5 4
A.PRAKASH (GL),PG & RESEARCH DEPARTMENT OF COMPUTER SCIENCE , ARIGNAR ANNA GOVERNMENT ARTS
COLLEGE , CHEYYAR-604 407 Page 5
In swap()Values X=4 and Y=5
In main()Values X=4 and Y=5
For Ex.
int k = 0;
int &kk = k; // kk is an alias for k
kk = 2; // same effect as k = 2
Example:
#include<iostream>
using namespace std;
void swap (int &, int &);
cout<<“\n Enter Values of X & Y:”;
cin>>x>>y;
swap(x,y);
cout<<“\n In main()Values X=”<<x <<“ and Y=”<<y;
return 0;
}
void swap(int &a, int &b)
{
int k;
k=a;
a=b;
b=k;
cout<<“\n In swap()Values X=”<<a <<“ and Y=”<<b;
}
Output:
A.PRAKASH (GL),PG & RESEARCH DEPARTMENT OF COMPUTER SCIENCE , ARIGNAR ANNA GOVERNMENT ARTS
COLLEGE , CHEYYAR-604 407 Page 6
2.5 Inline Functions:
When a function is declared as inline, the compiler copies the code of the
function in the calling function. i.e., function body is inserted in place of function call during
compilation.
Syntax:
The inline functions are similar to macros of C. The main limitation of macros is that they
are not functions, and errors are not checked at the time of compilation. The function offers
better type testing and does not contain limitations as present in macros.
#include <iostream>
using namespace std;
inline int Max(int x, int y)
{
return (x > y)? x : y;
}
int main( )
{
cout << "Max (20,10): " << Max(20,10) << endl;
cout << "Max (0,200): " << Max(0,200) << endl;
cout << "Max (100,1010):"<<Max(100,1010)<<endl;
A.PRAKASH (GL),PG & RESEARCH DEPARTMENT OF COMPUTER SCIENCE , ARIGNAR ANNA GOVERNMENT ARTS
COLLEGE , CHEYYAR-604 407 Page 7
return 0;
}
Output:
Max (20,10): 20
Max (0,200): 200
Max (100,1010):1010
Ex:
#include <iostream>
using namespace std;
int sum(int a, int b=10, int c=20, int d=30)
{
return a+b+c+d;
}
int main() {
int a=2,b=3,c=4,d=5;
cout<<"Sum:"<<sum(a,b,c,d)<<endl;
cout<<"Sum:"<<sum(a,b,c)<<endl;
cout<<"Sum:"<<sum(a,b)<<endl;
cout<<"Sum:"<<sum(a)<<endl;
return 0;
}
Output:
Sum:14
Sum:39
Sum:55
Sum:62
Const Arguments:
The constant variable can be declared using const keyword. The const keyword makes
variable value stable.
A.PRAKASH (GL),PG & RESEARCH DEPARTMENT OF COMPUTER SCIENCE , ARIGNAR ANNA GOVERNMENT ARTS
COLLEGE , CHEYYAR-604 407 Page 8
Ex. The following program generates an error
#include <iostream>
using namespace std;
int increment(const int a);
int main() {
int a=2;
cout<<"Incremented val:"<<increment(a);
return 0;
}
int increment( const int a)
{
return ++a;
}
Output:
error: increment of read-only parameter 'a'
function_name(array_name);
In this example, we are passing two arrays a & b to the function sum(). This function adds
the corresponding elements of both the arrays and display them.
#include <iostream>
using namespace std;
/* This function adds the corresponding
* elements of both the arrays and
* displays it.
*/
void sum(int arr1[], int arr2[]){
int temp[5];
for(int i=0; i<5; i++){
temp[i] = arr1[i]+arr2[i];
cout<<temp[i]<<endl;
}
}
int main(){
int a[5] = {10, 20, 30, 40 ,50};
A.PRAKASH (GL),PG & RESEARCH DEPARTMENT OF COMPUTER SCIENCE , ARIGNAR ANNA GOVERNMENT ARTS
COLLEGE , CHEYYAR-604 407 Page 9
int b[5] = {1, 2, 3, 4, 5};
//Passing arrays to function
sum(a, b);
return 0;
}
Output:
11
22
33
44
55
In this example we are passing a multidimensional array to the function square which
displays the square of each element.
#include <iostream>
#include <cmath>
using namespace std;
/* This method prints the square of each
* of the elements of multidimensional array
*/
void square(int arr[2][3]){
int temp;
for(int i=0; i<2; i++){
for(int j=0; j<3; j++){
temp = arr[i][j];
cout<<pow(temp, 2)<<endl;
}
}
}
int main(){
int arr[2][3] = {
{1, 2, 3},
{4, 5, 6}
};
square(arr);
return 0;
}
Output:
1
4
9
16
25
36
A.PRAKASH (GL),PG & RESEARCH DEPARTMENT OF COMPUTER SCIENCE , ARIGNAR ANNA GOVERNMENT ARTS
COLLEGE , CHEYYAR-604 407 Page 10
A structure variable can be passed to a function in similar way as normal argument.
Consider this example:
#include <iostream>
using namespace std;
struct Person {
char name[50];
int age;
float salary;
};
int main() {
Person p;
return 0;
}
void displayData(Person p) {
cout << "\nDisplaying Information." << endl;
cout << "Name: " << p.name << endl;
cout <<"Age: " << p.age << endl;
cout << "Salary: " << p.salary;
}
Output
Displaying Information.
Name: Bill Jobs
Age: 55
Salary: 34233.4
In this program, user is asked to enter the name , age and salary of a Person inside main() function.
Then, the structure variable p is to passed to a function using.
displayData(p);
A.PRAKASH (GL),PG & RESEARCH DEPARTMENT OF COMPUTER SCIENCE , ARIGNAR ANNA GOVERNMENT ARTS
COLLEGE , CHEYYAR-604 407 Page 11
The return type of displayData() is void and a single argument of type structure Person is passed.
Then the members of structure p is displayed from this function.
2.9 Recursion:
In many programming languages including C++, it is possible to call a function
from a same function. This function is known as recursive function and this programming
technique is known as recursion.
In recursion a function calls itself and the control goes to the same function and it
executes repeatedly until some condition is satisfied. In this type of recursive calls a
function starts with a new value every time.
Example:
#include<iostream>
using namespace std;
int main()
{
unsigned long int fact(int);
dint f,x; cout<<“\nEnter a Number:”;
cin>>x; f=fact(x);
cout<<“\nFactorial of ” <<x <<“ is ”<<f;
return 0;
}
unsigned long int fact(int a)
{
unsigned long factorial;
if(a==1)
A.PRAKASH (GL),PG & RESEARCH DEPARTMENT OF COMPUTER SCIENCE , ARIGNAR ANNA GOVERNMENT ARTS
COLLEGE , CHEYYAR-604 407 Page 12
return 1;
else
factorial=a*fact(a-1);
return factorial;
}
Output:
Enter a Number:6
Factorial of 6 is 720
2.10 Pointers:
Pointers are symbolic representation of addresses. They enable programs to
simulate call-by-reference as well as to create and manipulate dynamic data structures. It’s
general declaration in C/C++ has the format :
Syntax:
datatype *var_name;
int *ptr; //ptr can point to an address which holds int data
A.PRAKASH (GL),PG & RESEARCH DEPARTMENT OF COMPUTER SCIENCE , ARIGNAR ANNA GOVERNMENT ARTS
COLLEGE , CHEYYAR-604 407 Page 13
The reason we associate data type to a pointer is that it knows how many bytes the
data is stored in. When we increment a pointer, we increase the pointer by the size of data
type to which it points.
void geeks()
{
int var = 20;
// Driver program
int main()
{
geeks();
}
Output:
Value at ptr = 0x7ffcb9e9ea4c
A.PRAKASH (GL),PG & RESEARCH DEPARTMENT OF COMPUTER SCIENCE , ARIGNAR ANNA GOVERNMENT ARTS
COLLEGE , CHEYYAR-604 407 Page 14
Value at var = 20
Value at *ptr = 20
#include <bits/stdc++.h>
using namespace std;
//Pass-by-Value
int square1(int n)
{
//Address of n in square1() is not the same as n1 in main()
cout << "address of n1 in square1(): " << &n << "\n";
A.PRAKASH (GL),PG & RESEARCH DEPARTMENT OF COMPUTER SCIENCE , ARIGNAR ANNA GOVERNMENT ARTS
COLLEGE , CHEYYAR-604 407 Page 15
//Call-by-Reference with Pointer Arguments
int n2=8;
cout << "address of n2 in main(): " << &n2 << "\n";
square2(&n2);
cout << "Square of n2: " << n2 << "\n";
cout << "Change reflected in n2: " << n2 << "\n";
}
//Driver program
int main()
{
geeks();
}
Output:
A.PRAKASH (GL),PG & RESEARCH DEPARTMENT OF COMPUTER SCIENCE , ARIGNAR ANNA GOVERNMENT ARTS
COLLEGE , CHEYYAR-604 407 Page 16
In Function Overloading “Function” name should be the same and the arguments
should be different.
Function overloading can be considered as an example of polymorphism feature in
C++.
#include <iostream>
void print(int i) {
cout << " Here is int " << i << endl;
}
void print(double f) {
cout << " Here is float " << f << endl;
}
void print(char const *c) {
cout << " Here is char* " << c << endl;
}
int main() {
print(10);
print(10.10);
print("ten");
return 0;
}
Output:
Here is int 10
Here is float 10.1
Here is char* ten
How Function Overloading works?
• ELSE ERROR
A.PRAKASH (GL),PG & RESEARCH DEPARTMENT OF COMPUTER SCIENCE , ARIGNAR ANNA GOVERNMENT ARTS
COLLEGE , CHEYYAR-604 407 Page 17
2.12 FRIEND FUNCTIONS:
The private members cannot be accessed from outside the class. i.e.… a non member
function cannot have an access to the private data of a class. In C++ a non member
function can access private by making the function friendly to a class.
Definition:
Ex:
class sample
{
int x,y;
public:
sample(int a,int b);
friend int sum(sample s);
};
sample::sample(int a,int b)
{
x=a;y=b;
}
int sum(samples s)
{
int sum;
sum=s.x+s.y;
return 0;
}
void main()
{
Sample obj(2,3);
int res=sum(obj);
cout<< “sum=”<<res<<endl;
}
A.PRAKASH (GL),PG & RESEARCH DEPARTMENT OF COMPUTER SCIENCE , ARIGNAR ANNA GOVERNMENT ARTS
COLLEGE , CHEYYAR-604 407 Page 18
➢ 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.
➢ It can be declared either in the public or private part of a class without affecting
its meaning.
➢ Usually, it has the objects as arguments.
#include<iostream.h>
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;
X.setvalue();
cout<<”Mean value=”<<mean(X);
return 0;
}
write a program to find max of two numbers using friend function for two different classes:
#include<iostream>
using namespace std;
class sample2;
class sample1
{
int x;
public:
A.PRAKASH (GL),PG & RESEARCH DEPARTMENT OF COMPUTER SCIENCE , ARIGNAR ANNA GOVERNMENT ARTS
COLLEGE , CHEYYAR-604 407 Page 19
sample1(int a);
friend void max(sample1 s1,sample2 s2)
};
sample1::sample1(int a)
{
x=a;
}
class sample2
{
int y;
public:
};
sample2(int b);
friend void max(sample1 s1,sample2 s2)
Sample2::sample2(int b)
{
y=b;
}
void max(sample1 s1,sample2 s2)
{
If(s1.x>s2.y)
cout<<”Data member in Object of class sample1 is larger ”<<endl;
else
}
cout<<”Data member in Object of class sample2 is larger ”<<endl;
void main()
{
sample1 obj1(3);
sample2 obj2(5);
max(obj1,obj2);
}
A.PRAKASH (GL),PG & RESEARCH DEPARTMENT OF COMPUTER SCIENCE , ARIGNAR ANNA GOVERNMENT ARTS
COLLEGE , CHEYYAR-604 407 Page 20
friend complex add_complex(complex c1,complex c2);
};
complex::complex()
{
real=img=0;
}
complex::complex(float x,float y)
{
real=x;img=y;
}
complex add_complex(complex c1,complex c2)
{
complex t;
t.real=c1.real+c2.real;
t.img=c1.img+c2.img;
return t;
}
void complex::display ()
{
if(img<0)
{
img=-img; cout<<real<<"-i"<<img<<endl
}
else
{
}
}
int main()
{
cout<<real<<"+i"<<img<<endl complex obj1(2,3);
complex obj2(-4,-6);
complex obj3=add_compex(obj1,obj2);
obj3.display();
return 0;
}
Friend Class:
A class can also be declared to be the friend of some other class. When we
create a friend class then all the member functions of the friend class also become the
friend of the other class.
This requires the condition that the friend becoming class must be first declared or
defined (forward declaration).
A.PRAKASH (GL),PG & RESEARCH DEPARTMENT OF COMPUTER SCIENCE , ARIGNAR ANNA GOVERNMENT ARTS
COLLEGE , CHEYYAR-604 407 Page 21
#include <iostream.h>
class sample_1
{
friend class sample_2;//declaring friend class
int a,b;
public: void getdata_1()
{
cout<<"Enter A & B values in class sample_1";
cin>>a>>b;
}
void display_1()
{
cout<<"A="<<a<<endl; cout<<"B="<<b<<endl;
}
};
class sample_2
{
int c,d,sum;
sample_1 obj1;
public: void getdata_2()
{
}
obj1.getdata_1();
cout<<"Enter C & D values in class sample_2";
cin>>c>>d;
void sum_2()
{
sum=obj1.a+obj1.b+c+d;
}
void display_2()
{
cout<<"A="<<obj1.a<<endl;
cout<<"B="<<obj1.b<<endl;
cout<<"C="<<c<<endl;
cout<<"D="<<d<<endl;
cout<<"SUM="<<sum<<endl;
}
};
int main()
{
sample_1 s1;
A.PRAKASH (GL),PG & RESEARCH DEPARTMENT OF COMPUTER SCIENCE , ARIGNAR ANNA GOVERNMENT ARTS
COLLEGE , CHEYYAR-604 407 Page 22
s1.getdata_1();
s1.display_1();
sample_2 s2;
s2.getdata_2();
s2.sum_2();
s2.display_2();
}
Enter A & B values in class sample_1:1 2 A=1 B=2
Enter A & B values in class sample_1:1 2 3 4
Enter C & D values in class sample_2:A=1 B=2 C=3 D=4 SUM=10
A.PRAKASH (GL),PG & RESEARCH DEPARTMENT OF COMPUTER SCIENCE , ARIGNAR ANNA GOVERNMENT ARTS
COLLEGE , CHEYYAR-604 407 Page 23