Search code examples
c++-clioverloadingincrementref

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.


Solution

  • 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++.