Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overloading I/O operator C++

Tags:

c++

I'm trying to overload the << operator. I'm expecting the output to be InitializingHello WorldOut but it is just outputting Hello World. I can't figure out what is wrong with my code. Thanks for your help.

  #include <iostream>
  using namespace std;


  ostream &operator << (ostream &out, const char* &s)
  {
    out << "Initializing" << s << "Out";
    return out;
  }

  void main() {

    cout << "Hello World" << endl;
    system("Pause");
  }
like image 717
coolio Avatar asked Sep 19 '26 05:09

coolio


2 Answers

"Hello World" is actually of type const char[12], which can decay into an r-value (temporary) of type const char *, but your function takes a reference to a const char*, and as you may know, you cannot bind a reference to a non-const r-value. So your operator is not called, but instead the standard ostream &operator << (ostream &out, const char* s) is.

PS. Please do not write void main(). It should be int main() unless you are in an embedded system (not likely).

like image 149
rodrigo Avatar answered Sep 21 '26 17:09

rodrigo


There already is an overload for << with the exact same prototype. The compiler cannot decide which to use...

like image 38
Benoît Avatar answered Sep 21 '26 17:09

Benoît