0

Why do we overload operators ? Is it possible to add/subtract objects of a class without using overloaded '+' operator ?

2
Contributors
1
Reply
2
Views
7 Years
Discussion Span
Last Post by Narue
0

>Why do we overload operators ?
Syntactic sugar. It all becomes clear when you think about a case where the overload is vastly less awkward than the alternative:

#include <iostream>
#include <string>

int main()
{
  std::string hello = "Hello";
  std::string world = "world";

  // With overloaded << operator
  std::cout<< hello <<" "<< world <<"!"<< std::endl;

  // Without overloaded << operator
  std::endl (
    std::cout.write ( hello.c_str(), 5 )
             .write ( " ", 1 )
             .write ( world.c_str(), 5 )
             .write ( "!", 1 ) );
}

>Is it possible to add/subtract objects of a class without using overloaded '+' operator ?
Sure, if the class supports the operation. You can write add and subtract member functions just as easily as operator+ and operator- .

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.