When we write a program to solve a larger problem, we divide that larger problem into smaller sub problems and are solved individually to make the program easier. This concept is implemented using functions. Functions are used to divide a larger program into smaller subprograms such that program becomes easy to understand and easy to implement. A function is defined as follows.
Function is a subpart of program used to perform specific task and is executed individually.
Every C++ program must contain atleast one function called main(). However a program may also contain other functions.
The structure of the main function in a C++ program. Here's a simple breakdown of the main components:
Function Header: The line int main() is called the function header. It marks the start of the function definition.
Return Type: int indicates that the function will return an integer value.
Function Name: main is the name of the function. In C++ programs, main is a special function where the program starts executing.
Parameter List: The parentheses () contain the parameter list. In this case, it is empty, meaning the function doesn't take any input arguments.
Function Body: The part inside curly braces { } is the function body. It contains the statements that are executed when the function is called. In this case, the body contains:
cout << "Hello World\n"; to print "Hello World" on the screen.
return 0; which indicates the program ends successfully.
So, the main function is the starting point of the program, and it defines the code to execute. In simple terms, when you run a C++ program, the program begins by executing the code inside the main() function.
Every function has the following...
The function declaration tells the compiler about function name, data type of the return value and parameters. The function declaration is also called as function prototype. The function declaration is performed before main function or inside main function or inside any other function.
Function declaration syntax:
returnType functionName(parametersList);
In the above syntax, returnType specifies the datatype of the value which is sent as a return value from the function definition. The function Name is a user defined name used to identify the function uniquely in the program. The parameters List is the data values that are sent to the function definition.
Ex1: void display();
Ex2: int add(int,int);
The function definition provides the actual code of that function.
The function definition is also known as body of the function.
The actual task of the function is implemented in the function definition.
That means the actual instructions to be performed by a function are written in function definition.
The actual instructions of a function are written inside the braces "{ }".
The function definition is performed before main function or after main function.
Function definition syntax :
returnType functionName(parametersList)The function call tells the compiler when to execute the function definition.
When a function call is executed, the execution control jumps to the function definition where the actual code gets executed and returns to the same functions call once the execution completes.
The function call is performed inside main function or inside any other function or inside the function itself.
Function call syntax –
functionName(parameters);
Ex: display();
add(10,20);
C++ introduces a new kind of variable known as Reference Variable. It provides an alias (alternative name) for a previously defined variable.
A reference variable must be initialized at the time of declaration.
This establishes the correspondences between the reference and the data object which it name.
When a reference is created, you must initialize it with another variable
Declaration:
[data_type] &[reference_variable]=[regular_variable];
regular_variable is a variable that has already initialized, and reference_variable is an alternative name (alias) to represent the regular_variable.
Ex:- int a;
int &b=a;
Consider the example program
#include<iostream>
using namespace std;
int main()
{
int a=100;
int &b=a;
int &c=b;
cout<<a<<”\t”<<b<<”\t”<<c<<endl;
c=200;
cout<<a<<”\t”<<b<<”\t”<<c<<endl;
return 0;
}
output:
100
100
100
200
200
200
There are two types of parameters and they are as follows...
Actual Parameters
Formal Parameters
The actual parameters are the parameters that are specified in calling function. The formal parameters are the parameters that are declared at called function.
When a function gets executed, the copy of actual parameter values are copied into formal parameters.
There are three methods to pass parameters from calling function to called function and they are as follows.
In the call by value mechanism the values from the actual parameters are copied into the formal parameters.
We pass normal variables as the parameters in this call by value mechanism.
The changes or modifications done to the formal parameters will not affect the values of the actual parameter.
We use call by value mechanism when the actual parameters are independent of the formal parameters.
Program on call by value:-
#include<iostream>
using namespace std;
void swap(int ,int );
int main()
{
int a=500, b=100;
cout<<"Before Swapping Value of a is: "<<a<<" b is: "<<b<<endl;
swap(a, b);
cout<<"after Swapping Value of a is: "<<a<<" b is: "<<b<<endl;
return 0;
}
void swap(int x, int y)
{
int temp;
temp=x;
x=y;
y=swap;
cout<<"after Swapping Value of x is: "<<x<<" y is: "<<y<<endl;
}
output:
Before Swapping Value of a is: 500 b is: 100
after Swapping Value of x is: 100 y is: 500
after Swapping Value of a is: 500 b is: 100
In the call by Address mechanism the address of actual parameters is passed into formal parameters.
We pass pointer variables as the parameters in this call by reference mechanism.
Here the formal parameters are declared as the pointer variables, which are used to hold (or) store the addresses of the other variables.
The changes or modifications done to the formal parameters will effect the values of the actual parameter.
The function is called by passing the address of actual parameters using the address of operator (&).
The * (asterisk) operator is used for declaring pointer variables as well as accessing value at the specified location.
Program on call by Address:
#include<iostream>
using namespace std;
void swap(int *,int * );
int main()
{
int a=500, b=100;
cout<<"Before Swapping Value of a is: "<<a<<" b is: "<<b<<endl;
swap(&a, &b);
cout<<"after Swapping Value of a is: "<<a<<" b is: "<<b<<endl;
return 0;
}
void swap(int *x, int *y)
{
int temp;
temp=*x;
*x=*y;
*y=temp;
}
output:
Before Swapping Value of a is: 500 b is: 100
after Swapping Value of a is: 100 b is: 500
The call by reference method of passing arguments to a function copies the reference of an argument into the formal parameter.
We pass reference variables as the parameters in this call by reference mechanism.
Inside the function, the reference is used to access the actual argument used in the call.
This means that changes made to the parameter affect the passed argument.
Program on Call by reference:
#include<iostream>
using namespace std;
void swap(int &,int &);
int main()
{
int x=500, y=100;
cout<<"Before Swapping Value of x is: "<<x<<" y is: "<<y<<endl;
swap(x, y);
cout<<"after Swapping Value of x is: "<<x<<" y is: "<<y<<endl;
return 0;
}
void swap(int &x, int &y)
{
int temp;
temp=x;
x=y;
y=temp;
}
output:
Before Swapping Value of x is: 500 y is: 100
after Swapping Value of x is: 100 y is: 500
The scope resolution operator in C++ is used to define the scope of a function or variable.
The scope resolution operator is represented using (: :).
It helps to specify which function or variable we are referring to when there are multiple definitions with the same name in different scopes.
The scope resolution operator (: :) is used to specify where a variable or function belongs
Class Scope Resolution: When defining a class method outside the class definition, the scope resolution operator is used to specify that the function belongs to that class.
Example Program
class MyClass
{
public:
void myMethod();
};
// Function definition outside the class using scope resolution void
MyClass::myMethod()
{
cout << "Hello from MyClass" << endl;
}
The inline functions are a C++ enhancement feature to increase the execution time of a program. Functions can be instructed to compiler to make them inline so that compiler can replace those function definition wherever those are being called. Compiler replaces the definition of inline functions at compile time instead of referring function definition at runtime.
NOTE- This is just a suggestion to compiler to make the function inline, if function is big (in term of executable instruction etc.) then, compiler can ignore the “inline” request and treat the function as normal function.
Syntax:
inline return_type function_name(arguments)
{
---- (body of statements)
}
Program:
#include <iostream>
using namespace std;
inline void hello()
{
cout<<"hello";
}
int main()
{
hello(); //Call it like a normal function...
}
C++ allows us to assign default values to function arguments, which is helpful in case a matching argument is not given by the user in function call statement.
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 with default value
Syntax
return_type function_name(type arg1,type arg2=default_value,...);
//here, arg2 is default argument....
Following is a simple C++ example to demonstrate use of default arguments
#include<iostream>
using namespace std;
void sum(int x ,int y=20,int z=30 );
int main()
{
sum(10,20,30);
sum(10,20);
sum(40);
}
void sum(int x,int y,int z)
{
cout<<"sum="<<x+y+z<<endl;
}
Output:
sum=60
sum=80
sum=110
In C++, it is possible to make more than one function with same name, this concept is known as function overloading. We can use same function name for different purpose with different number and types of arguments.
In function overloading function names will be same but Types of arguments, Order of arguments, Number of arguments must be different.
The C++ compiler selects the proper function by examining the number, types and order of the arguments in the call. Function overloading is commonly used to create several functions of the same name that perform similar tasks but on different data types.
Following advantages to use function overloading in your program:
Eliminating the use of different function names for the same operations.
Helps to understand, debug and group easily.
Easy maintainability of the code.
Better understandability of the relationship b/w the program and the outside world.
Points to remember
Function overloading does not depend on return type of function.
Program:
#include<iostream>
using namespace std;
int sum(int, int);
double sum(double, double);
int main()
{
sum(10,20);
sum(10.5,20.5);
return 0;
}
int sum(int x,int y)
{
cout<< x+y<<endl;
}
double sum(double x,double y)
{
cout<<x+y<<endl;
}
Output:
30
31
Friend function is a special type of function, which declares inside the class. Friend function can access the private, protected and public data of the class.
A keyword friend is used before return type of the function declaration/prototype.
Friend function will be defined outside the class without specifying the class name.
Friend function will be invoked like normal function, without any object.
Declaration Syntax of friend function in C++
class class_name
{
... .. ...
friend return_type function_name(argument/s);
... .. ...
}
Definition Syntax of friend function in C++
return_type functionName(argument/s)
{
... .. ...
// Body of the friend function
... .. ...
}
We can define the friend function as a normal function to access the data of the class. No friend keyword is used in the definition
Friend function calling syntax in C++
functionName(Object name)
C++ program to demonstrate example of friend function with class.
#include<iostream>
using namespace std;
class Sample
{
int a,b;
friend void print(Sample);
};
void print(Sample s)
{
int add;
s.a=10;
s.b=20;
add=s.a+s.b;
cout<<"add= "<<add;
}
int main()
{
Sample s1;
print(s1);
return 0;
}
Output:
sum=30
A constructor is a special member function, which has the same name as that of the class name.
The constructor functions have some special characteristics. They are:
Constructors must be declared in public section.
Constructors are invoked automatically when the objects are created.
Constructors do not have return types, not even void. Therefore, they cannot return any values.
Constructors may or may not contain arguments. If a constructor does not contain arguments then it is called as default arguments and the constructors which contain arguments are called as parameterized constructors.
Constructors cannot be inherited.
Constructors make implicit calls to the operators new and delete when memory allocation is required.
Syntax:
class classname
{
public:
classname()
{
---
---
---
}
};
If the constructor does not contain any arguments then it is called default constructor.
Syntax:
class classname
{
public:
classname() // Default Constructor
{
---
---
---
}
};
Program on Constructors / Program on default constructor
#include<iostream>
using namespace std;
class sample
{
public:
sample()
{
cout<<"Welcome to constructors topic";
}
};
int main()
{
sample s;
}
Output:
Welcome to constructors topic
The constructor that can take arguments are called parameterized constructor.
The arguments can be separated by commas and they can be specified within braces similar to the argument list in function.
In case of parameterized constructor, we must provide the appropriate arguments to the constructor when an object is declared.
Syntax:
class classname
{
public:
classname(argument list) // Parameterized Constructor
{
---
---
---
}
};
Program on parameterized constructor
#include<iostream>
using namespace std;
class sample
{
public:
sample()
{
cout<<"Welcome to Parameterized constructors "<<endl;
}
sample(int x)
{
cout<<”value of x=”<<x;
}
};
int main()
{
sample s; sample s1(10);
}
Output:
Welcome to Parameterized constructors
value of x=10
These are special type of Constructors which takes an object as argument, and is used to copy values of data members of one object into other object.
Initialization of an object through another object is called copy constructor.
In other words, copying the values of one object into another object is called copy constructor.
Syntax:
Class Class_Name
{
Constructor_name(class_name &obj_name)
{
//Statements
}
};
Here, obj is a reference to an object that is being used to initialize another object.
Program on Copy Constructor
#include<iostream>
using namespace std;
class sample
{
int m;
public:
sample(int x)
{
m=x;
}
sample(sample &x)
{
m=x.m;
}
void display()
{
cout<<”m=”<<m<<endl;
}
};
int main()
{
sample s1(10);
sample s2(s1); // sample s2=s1;
s1.display();
s2.display();
}
Output:
m=10
m=10
Constructor allocates the memory for an object.
Destructor deallocate the memory occupied by an object. Like constructor, destructor name and class name must be same, preceded by a tilde(~) sign. Destructor take no argument and have no return value.
Constructor is invoked automatically when the object created. Destructor is invoked when the object goes out of scope.
In other words, Destructor is invoked, when compiler comes out form the function where an object is created.
Syntax:
class class_name
{
public:
~ class_name( )
{
//Body of Destructor
}
};
Program
#include<iostream>
using namespace std;
class Demo
{
public:
Demo()
{
cout<<”Welcome to constructors”<<endl;
}
~Demo()
{
cout<<” Object Destroyed”;
}
};
int main()
{
Demo d;
cout<<” main function()”<<endl;
return 0;
}
Output:
Welcome to constructors
main function()
Object Destroyed