0

I see two different formats for operator overloading for the operator () overload and the ostream << overload and would like to know why this is.

#include <iostream>
using namespace std;

class printData {

public:

    std::string str = "hello";

    operator std::string () const; // {return str;}
};

printData::operator std::string () const {return str;}

std::ostream& operator << (ostream& os, printData const& p){
    return os << p.str;
}

int main(void) {
    printData pd{};

//
    std::string str2 = pd;          // str2 = pd.str from operator() overload
    std::cout << str2 << std::endl; // output "hello"
    std::cout << pd << std::endl;   // output "hello" (from ostream overload)

    return 0;
}

The operator() overload has the return type std::string AFTER the keyword operator. The ostream overload has the return type ostream& BEFORE the keyword operator. Why are these overloads structured differently or am I missing something? Thank you in advance.

D Turner
  • 35
  • 7
  • _"... `operator()`..."_ is not `operator()` but a conversion operator to `std::string` (similar to a cast) see: http://en.cppreference.com/w/cpp/language/cast_operator – Richard Critten Mar 15 '18 at 22:01
  • @RichardCritten thank you for taking a look at this, I have provided a simple example to illustrate my question. The actual wokings of the operator() overload should not be the debate as it is as simple an example as possible so as not to cloud my question – D Turner Mar 15 '18 at 22:30
  • You don't have an `operator()` in the above code, you need to read the link I posted. – Richard Critten Mar 15 '18 at 22:33
  • @RichardCritten OK ty, will do – D Turner Mar 15 '18 at 22:41
  • @RichardCritten Thank you so much, so helpful. I suggest you formally answer my question so I can up vote it. Or let me buy you a beer :) Thank you so so much. – D Turner Mar 15 '18 at 23:05

0 Answers0