Reputation: 105
#include "stdafx.h"
#include "iostream"
using namespace std;
class complex
{
int real;
int img;
public:
complex(int x = 0, int y = 0)
{
cout << "Inside Prama" << endl;
real = x;
img = y;
}
complex operator+(complex x)
{
complex temp;
temp.real=real + x.real;
temp.img=img + x.img;
return temp;
}
void display()
{
cout << real << ' ' << img << endl;
}
};
int main()
{
class complex c1(5,6), c2(7,8),c3(7,7),c4;
c1.display();
c2.display();
c3.display();
c4 = c1+c2+c3;
c4.display();
return 0;
}
for above operator overloading code following is the output:
why that parameterized constructor is called at the time of adding of the objects.I am not getting the reason for that
Upvotes: 2
Views: 119
Reputation: 122178
Just summarizing comments...
Here
complex operator+(complex x)
{
complex temp;
temp.real=real + x.real;
temp.img=img + x.img;
return temp;
}
complex temp;
calls the constructor and thats the output you see. Typically you'd pass x
as const
reference to avoid the copy, but as you need a copy anyhow you can use x
:
complex operator+(complex x)
{
x.real +=real;
x.img +=img;
return x;
}
This will only invoke the compiler generated copy constructor when you call the operator.
There are more subtleties to consider. Using x
instead of making a local copy inhibits named return value optimization. Also it is common to implement operator+
in terms of operator+=
and operator+
can be a free function then. Note that operator+=
can be more efficient, because no copy is needed at all. For more details on operator overloading in general I refer you to What are the basic rules and idioms for operator overloading?
PS: "parametrized constructor" is a term I have seen only in poor misleading tutorials so far. It is not an official term. The relevant term here is default constructor. complex(int x = 0, int y = 0)
is a default constructor because it can be called without parameters. It is a good example for why "parametrized constructor" does not convey lots of meaning and is rather misleading.
Upvotes: 2