0fnt
0fnt

Reputation: 8661

assignment operator overloading skipped / not happening

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.

Upvotes: 1

Views: 358

Answers (3)

Vijay
Vijay

Reputation: 67221

cases where a copy constructor is called:

when you return an object
when you pass an object to some function
X b(a);
X b = a;

cases where an assignment operator overload function is called is

X b; b=a;//where a is already existing object and already intialised.

Upvotes: 1

Sion Sheevok
Sion Sheevok

Reputation: 4217

If you declare a variable and initialize it on the same line, it will still call the copy constructor.

The are two initialization syntax:

X a;
X b(a);

X a;
X b = a;

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.

Upvotes: 3

Terry Mahaffey
Terry Mahaffey

Reputation: 11981

What's going on is that,

A p = q + r;

Calls the copy constructor of A, not the assignment operator. Yes, it's weird. It's the same as if you had typed this:

A p(q + r);

Upvotes: 1

Related Questions