Overloading of function-call operator in C++
In this article, we will discuss the Overloading of the function-call operators in C++.
- The function call operator is denoted by “()” which is used to call function and pass parameters. It is overloaded by the instance of the class known as a function object.
- When the function call operator is overloaded, an operator function is created that can be used to pass parameters.
- It modifies that how the operator is fetched by the object.
- In Object-Oriented Languages, operator() can be treated as a normal operator, and objects of a class type can call function (named operator()) like making a function call to any other overloaded operator.
- When the function call operator is overloaded, a new way to call a function is not created rather an operator() function is created that can be passed an arbitrary number of parameters.
Program:
Below is the program of taking input in a matrix using friend functions first to overload insertion operator and extraction operator and then overloading operator() for taking input for the ith row and the jth column of the matrix and displaying value at the ith row and the jth column stored in the matrix:
C++
#include <bits/stdc++.h>
#include <iostream>
using namespace std;
#define N 3
#define M 3
class Matrix {
private :
int arr[N][M];
public :
friend istream& operator>>(
istream&, Matrix&);
friend ostream& operator<<(
ostream&, Matrix&);
int & operator()( int , int );
};
istream& operator>>(istream& cin,
Matrix& m)
{
int x;
for ( int i = 0; i < N; i++) {
for ( int j = 0; j < M; j++) {
cin >> m(i, j);
}
}
return cin;
}
ostream& operator<<(ostream& cout,
Matrix& m)
{
for ( int i = 0; i < N; i++) {
for ( int j = 0; j < M; j++) {
cout << m(i, j) << " " ;
}
cout << endl;
}
return cout;
}
int & Matrix::operator()( int i, int j)
{
return arr[i][j];
}
int main()
{
Matrix m;
printf ( "Input the matrix:\n" );
cin >> m;
printf ( "The matrix is:\n" );
cout << m;
return 0;
}
|
Output:
Last Updated :
19 Apr, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...