Anon
Anon

Reputation: 1354

cli/c++ increment operator overloading

i have a question regarding operator overloading in cli/c++ environment

static Length^ operator++(Length^ len)
{
   Length^ temp = gcnew Length(len->feet, len->inches);
   ++temp->inches;
   temp->feet += temp->inches/temp->inchesPerFoot;
   temp->inches %= temp->inchesPerFoot;
   return temp;
}

(the code is from ivor horton's book.)

why do we need to declare a new class object (temp) on the heap just to return it? ive googled for the info on overloading but theres really not much out there and i feel kinda lost.

Upvotes: 0

Views: 994

Answers (2)

Alex F
Alex F

Reputation: 43331

This is the way operator overloading is implemented in .NET. Overloaded operator is static function, which returns a new instance, instead of changing the current instance. Therefore, post and prefix ++ operators are the same. Most information about operator overloading talks about native C++. You can see .NET specific information, looking for C# samples, for example this: http://msdn.microsoft.com/en-us/library/aa288467(v=vs.71).aspx .NET GC allows to create a lot of lightweight new instances, which are collected automatically. This is why .NET overloaded operators are more simple than in native C++.

Upvotes: 1

Kornel Kisielewicz
Kornel Kisielewicz

Reputation: 57585

Yes, because you're overloading POST-increment operator here. Hence, the original value may be used a lot in the code, copied and stored somewhere else, despite the existance of the new value. Example:

store_length_somewhere( len++ );

While len will be increased, the original value might be stored by the function somewhere else. That means that you might need two different values at the same time. Hence the creation and return of a new value.

Upvotes: 1

Related Questions