Click to See Complete Forum and Search --> : Operator Overloading


PBanta
January 15th, 2007, 09:09 PM
What is the difference between using "*" and"&" in operator overloading of a managed class? The two code examples below compile on my .Net compiler, but I don't know what the difference is. Would somebody explain?

Thanks,
Paul

public __gc class Complex
{
private:

float real;
float imaginary;

// . . .

public:

static Complex* op_Assign( Complex* lhs, float real )
{
// I think the code should be like this.
lhs->real = real;
lhs->imaginary = 0.0f;
return lhs;
}

} // end class Complex

Compare with the code below which uses "Complex&" in the overloaded operator. Both compile, but I suspect they are different in how they work.

public __gc class Complex
{
private:

float real;
float imaginary;

// . . .

public:

static Complex& op_Assign( Complex& lhs, float real )
{
// I think the code should be like this.
lhs.real = real;
lhs.imaginary = 0.0f;
return lhs;
}

} // end class Complex

I added code to the two methods in question. I think the code is right, but am not completely sure. I may be answering my own question. It looks like the two different signatures have some affect on the code inside the method. But more than that, I would think that the different signatures affect how the methods are called. Using the "*" operator, I think you would call it with:

Complex* c1 = new Complex;
Complex* c2;
c2 = c1 = 5.0f;

Using the "&" operator, I think you would call it with:

Complex c1;
Complex c2;
c1 = c2 = 5.0f;

Is this right? Am I close?

cilu
January 16th, 2007, 05:41 AM
Yes, there is a difference: the first returns a pointer, the second a reference. Can you post the actual implementation of the two operators?

Is there a way to make my code look indented. In the editor I indented the code, but it doesn't show the indentation when I preview.
Yes, there is: use code tags (see the link in my signature).

PBanta
January 16th, 2007, 01:34 PM
I added code to the two methods in my original post. I have a guess what the difference is (see modified original post), but am not certain. Is my description in original post correct?

cilu
January 16th, 2007, 04:22 PM
The first one should be the correct signature. Take a look at this article and its paragraph about overloading operators.

http://msdn.microsoft.com/msdnmag/issues/02/02/ManagedC/default.aspx