• python
  • javascript
  • reactjs
  • sql
  • c#
  • java
Facebook Twitter Instagram
Devs Fixed
  • python
  • javascript
  • reactjs
  • sql
  • c#
  • java
Devs Fixed
Home » Resolved: Writing to file using overloaded operator

Resolved: Writing to file using overloaded operator << - problem with recursion

0
By Isaac Tonny on 18/06/2022 Issue
Share
Facebook Twitter LinkedIn

Question:

I´m currently learning C++ and I decided to try to write my own “log tool”. My goal is, that I can write just something like this:

logger<<"log message"; [/code]

I have this problem – when I wrote operator << overloading function, the IDE compiler warned me, that it is infinite recursion.
Here is the code of operator overloading:

Logger &operator<<(Logger &logger, char *message) { logger << message << "Log message"; return logger; } [/code]

And function is in class declared as friend:

friend Logger &operator<<(Logger &logger, char *message); [/code]

Why is this code infinite recursion? Maybe I just can´t see some trivial mistake…
Thank you for your answers.

Answer:

Logger &operator<<(Logger &logger, char *message) [/code]

This declares an operator<< overload. It takes a left-hand side parameter that’s a Logger &, and a right-hand side parameter that’s a char *, that’s what this means in C++.

logger << message [/code]

And this invokes the << operator. Amongst all the defined operator overloads for <<, there is one operator overload that will work here: this particular operator overload takes a left-hand side parameter that’s a Logger & — and this logger object meets this criteria smashingly well — and a right-hand side parameter that’s a char * — that’s equally met well by the message object.
In other words, this calls the same operator<< overload, hence the infinite recursion.

If you have better answer, please add a comment about this, thank you!

c++
Share. Facebook Twitter LinkedIn

Related Posts

Resolved: Java Virtual Machines deleted

27/03/2023

Resolved: PyCharm cannot see my newly compiled .pyc see on import

27/03/2023

Resolved: I am facing ERR_HTTP2_PROTOCOL_ERROR on my website

27/03/2023

Leave A Reply

© 2023 DEVSFIX.COM

Type above and press Enter to search. Press Esc to cancel.