Operator overloading for heap objects.

Dec 10, 2009 at 2:04pm
Hi all,

Operator Overloading for Stack members

In MyClass.h
1
2
3
4
class MyClass
{
       MyClass operator +(MyClass inVar);
};


In MyClass.cpp
1
2
3
4
5
6
7
8
MyClass MyClass::operator +(MyClass inVar)
{
       MyClass outVar;

       //do som thing

       return outVar;
}


Usage :
1
2
MyClass temp1 , temp2;
temp3 = temp1+temp2;


This work I know,but my doubt is for the heap object please check the one below.

-------------------------------------------------------------------

Operator Overloading for Heap members

In MyClass.h
1
2
3
4
class MyClass
{
       MyClass* operator +(MyClass* inVar);
};


In MyClass.cpp
1
2
3
4
5
6
7
8
MyClass* MyClass::operator +(MyClass* inVar)
{
       MyClass* outVar;

       //do som thing

       return outVar;
}


Usage :

1
2
3
MyClass* temp1 = new MyClass();
MyClass* temp2 = new MyClass();
MyClass* temp3 = temp1+temp2;


If I try to do like above it is truing to address instead of
performing operator overloading.


Can any one help me on this,
-Madhu
Dec 10, 2009 at 3:33pm
If you tried to take the overloading out off the class you'd get
error C2803: 'operator +' must have at least one formal parameter of class type
meaning that you can't overload an operator for two pointers. I think here temp3 = (*temp1)+temp2; should work (I'm not sure if you realy need the parentheses).
Last edited on Dec 10, 2009 at 3:33pm
Dec 10, 2009 at 4:01pm
Yes, typically one does not create these kinds of overloads for pointers. The reason being is that
you cannot do:

1
2
3
int* i1 = new int( 5 );
int* i2 = new int( 6 );
int   i3 = i1 + i2;


and expect it to compile, let alone set i3 to 11.
Dec 11, 2009 at 5:05am
Hi hamsterman & jsmith,
Thanks for the replies.

I convinced with hamsterman reply,and jsmith can you please elaborate how i3 is set to 11.


Thanks,
Madhu.
Dec 11, 2009 at 5:33am
jsmith said that it wouldn't be 11.

Anyway, I would advise against this approach. Pointers are pointers, not objects. If you want to overload operators for your class, those operators should work with objects unless you are specifically doing something related to pointers. If you're dealing with pointers, just put the * before them:

 
MyClass temp3 = *temp1 + *temp2;


Sure it's extra typing, but the code is much more clear and logical.
Topic archived. No new replies allowed.