I’m trying to create a library for some work and am using operator overloading for assignment operation.
Supposed X and Y are two instances of the class that has = overloaded thus:
A& A::operator=(A &rhs)
{
A::assign(*this, rhs);
return *this;
}
When I do this:
A z;
z = x + y; // x and y are other instances of class A
everything is fine, however, when I do a `
A p = q + r;
the overloaded routine does not get called. I’m not very experienced with operator overloading, can somebody explain whats happening. One explanation might be that p is just an alias for q + r object created already, however, z creates a new instance of class A and hence operator overloading kicks in when z is assigned to. Sort of like:
#include <iostream>
using namespace std;
class X
{
public:
X();
};
X::X()
{
cout<<"called"<<endl;
}
int main(int argc, char *argv[])
{
X e; X f;
X g = e;
}
where called gets printed only twice, once each for e and f, and does not get printed for g.
If that’s the case, can somebody suggest a way to trigger operator overloading for p.
Thanks.
If you declare a variable and initialize it on the same line, it will still call the copy constructor.
The are two initialization syntax:
There are slight differences as to what they mean, but in most cases they do the same. The difference is whether or not the compiler is guaranteed to avoid certain constructions/destructions. In either case, the copy constructor will be called, because your are constructing an object. I can’t quite remember what the details are as for the difference in guarantees.