Home »
C++ programming »
C++ find output programs
C++ Operator Overloading | Find output programs | Set 4
This section contains the C++ find output programs with their explanations on C++ Operator Overloading (set 4).
Submitted by Nidhi, on July 02, 2020
Program 1:
#include <iostream>
using namespace std;
class Test {
float A;
public:
Test(float a)
{
A = a;
}
void operator++(int)
{
A++;
}
void print()
{
cout << A << endl;
}
};
int main()
{
Test T1(10.5F);
T1++;
T1.print();
return 0;
}
Output:
11.5
Explanation:
Here, we create a Test class that contains data member A of float type. And, we defined a default constructor and member function print() to print the value of A, also defined member function to overload post-increment operator by passing dummy argument int. Without the dummy argument, the function will be overloaded for the pre-increment operator.
Program 2:
#include <iostream>
using namespace std;
class Test {
float A;
public:
Test()
{
A = 0.0F;
}
Test(float a)
{
A = a;
}
void operator++(float)
{
A++;
}
void print()
{
cout << A << endl;
}
};
int main()
{
Test T1(10.5F);
T1++;
T1.print();
return 0;
}
Output:
main.cpp:17:26: error: postfix ‘void Test::operator++(float)’
must take ‘int’ as its argument
void operator++(float)
^
main.cpp: In function ‘int main()’:
main.cpp:31:7: error: no ‘operator++(int)’ declared for
postfix ‘++’ [-fpermissive]
T1++;
~~^~
Explanation:
It will generate compilation error, because, to overload post-increment operator, we need to pass int as a dummy argument. Otherwise, it will generate an error.
Program 3:
#include <iostream>
using namespace std;
class Test {
float A;
public:
Test(float a)
{
A = a;
}
void operator<<()
{
cout << A << endl;
}
};
int main()
{
Test T1(10.5F);
T1 << ;
return 0;
}
Output:
main.cpp:13:21: error: ‘void Test::operator<<()’
must take exactly one argument
void operator<<()
^
main.cpp: In function ‘int main()’:
main.cpp:22:11: error: expected primary-expression before ‘;’ token
T1 << ;
^
Explanation:
It will generate compilation error, because, to overload the "<<" operator, we need to pass exactly one argument to the overloaded function.