tags:

views:

72

answers:

3

When overloading a "=" operator for a class, the usual syntax is:

ClassA ObjA, ObjB;

ObjA = ObjB;

But what about pointers ??

Class *PtrA, *PtrB;

PtrA->operator=(PtrB)

Is the above calling convention correct assuming the = operator in ClassA is defined for pointer on class (ClassA* operator=(const ClassA* obj)) ??

+3  A: 

Usually the assignment operator will be defined only for the class, and not the pointers, and then you can do:

*ptrA = *ptrB;
David Rodríguez - dribeas
However, Is PtrA->operator=(PtrB) calling convention correct ??
de costo
Assignment operators rarely are written to take pointers, usually they take const references. So I'd say this is the best answer, and your example `PtrA->operator=(PtrB)` should be avoided.
AshleysBrain
`*ptrA = *ptrB` is equivalent to `ptrA->operator=(*ptrB)`, but definitely preferred
Chris Dodd
To directly answer @de costo, your form of the statement is incorrect (from a convention standpoint). If for some reason you really don't want to use the typical `*ptrA = *ptrB`, use `ptrA->operator=(*ptrB)`.
dash-tom-bang
+2  A: 

Not that in your example

Class *PtrA, *PtrB;

PtrA->operator=(PtrB)

You are not passing in an instance of PtrB, you are passing in a pointer to a PtrB;

Actually of course your code doesnt really make sense. You cannot say

Class *PtrA, *PtrB;

I think you mean

Class A
{
}
Class B
{
  B operator=(const A &rhs){...}
}

A *ptra = ...
B *ptrb = ...

In this case you can go

*ptrb = *ptra;

or

ptrb->operator=(*ptra);

you certainly cannot go

ptrb->operator=(ptra)

or (the equivalent simple syntax)

*ptrbb = ptra
pm100
+1  A: 

If the assignement operator in ClassA accepts an argument of type ClassA * (or const ClassA *), then you can call it as either

 PtrA->operator =(PtrB);

or as

*PtrA = PtrB;

The latter is more natural way to use the assigment operator for obvious reasons.

However, defining the assignment operator to accept an argument of type ClassA * is a rather bizzare thing to do. Normally, assignment operator of ClassA would accept an argument of type const ClassA & and be invoked as

*PtrA = *PtrB;
AndreyT