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 anoperator<<
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!