How to overload operator<< with a reference pointer on the RHS?

I am trying to understand how to correctly overload the operator << with a pointer variable on the RHS, using a reference parameter. Here is an example code:

#include <iostream>
using namespace std;

class A
{
 public:
   void print(ostream& out) const { out << "Hello World!"; }
};

ostream& operator<<(ostream& out, const A*& handle)
{
   handle->print(out);
   return out;
}

int main() {
   A *a = new A();
   cout << a << endl;
   delete a;
}

I am assuming that the result should be Hello World!. Instead, the program prints the address of the object a 0x7f9bc6405be0, so apparently cout << a is not calling my overloading function.

Could anyone please explain why my definition of overloading << is not working as I expected?



Read more here: https://stackoverflow.com/questions/68476065/how-to-overload-operator-with-a-reference-pointer-on-the-rhs

Content Attribution

This content was originally published by C.-C. Yang at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: