CPP Language / Functions

It is a set of lines of code used to perform a particular task.

Simple function call
Calling a function by value / reference is called as Simple function call.

Function Type Program Output
Call by Value
#include <iostream>
using namespace std;
int addition (int a, int b)
{
return a+b;
}
int main ()
{
cout << addition (2,3);
}

The result is 5
Call by reference
#include <iostream>
using namespace std;
int addition ()
{
return 2+3;
}
int main ()
{
cout << "The result is " <<
addition ();
}

The result is 5

Inline Function
It is used with classes. In a inline function, the compiler places a copy of the code of that function at each point where the function is called at compile time. Any correction of inline function could require to recompile it because compiler would need to replace all the code once again otherwise it will continue with old functionality. To inline a function uses a keyword “inline” before the function name.

Program Output

#include
using namespace std;
inline int Max(int x, int y)
{
return (x > y)? x : y;
}
int main()
{
cout << "Max (20,10): " << Max(20,10);
return 0;
}

Max (20,10): 20

Overloading of functions
It is a process of having a same function name with different parameters / arguments.
There are 2 types of Overloading of functions. They were

1. Function Overloading(methods, constructors).
2. Operator Overloading.

overloading Type Program Output
Function overloading
#include
using namespace std;
class Addition
{
public:
int sum(int num1,int num2)
{
return num1+num2;
}
int sum(int num1,int num2, int num3)
{
return num1+num2+num3;
}
};

int main(void)
{
Addition obj;
cout< cout< return 0;
}

35
190
Operator overloading
#include
using namespace std;
class Test
{
private: int a;
public:
Test(): a(8){}
void operator ++()
{ a = a+2; }

void Print()
{ cout<<"The Number : "< };

int main()
{
Test tt;
++tt; // calling of a function "void operator ++()"
tt.Print();
return 0;
}

10

Default arguments
These are the parameters / values that may / may not be passed to a function. If they are passed to a function it may / may not use theses parameters / values. If not the function will take the default parameters / values.

Program Output

#include
using namespace std;

// Sum function with 2 default arguments (c,d)
int sum(int a, int b, int c=0, int d=0)
{ return (a + b + c + d); }

int main()
{
cout << sum(10, 15) << endl;
cout << sum(10, 15, 25) << endl;
cout << sum(10, 15, 25, 30);
return 0;
}


25
50
80

Friend function
If you want to define a function outside a class declare the function with ‘friend’ keyword in front of it.

Program Output

#include
using namespace std;
class Box
{
double width;
public:
friend void pw ( Box boxobj);
void setWidth( double wid );
};
void Box::setWidth( double wid )
{ width = wid;}
void pw( Box boxobj ) {
cout << " Box Width: " << boxobj.width ;
}

int main()
{
Box box;
box.setWidth(5.0);
pw ( box );
return 0;
}

Box Width: 5.0


Home     Back