#include<iostream>
using namespace std;
class aClass
{
public:
char *message;
aClass(const char *message);
~aClass(){delete[] message;}
};
aClass::aClass(const char* newmessage)
{
message = new char[strlen(newmessage) +1];
strcpy(message,newmessage);
}
const ostream& operator<<(const ostream& o, const aClass &a)
{
o << a.message;
return o;
}
int main()
{
aClass b("Hello");
cout << b;
}
Can someone explain to me why the code above produces an infinite loop?
Because you have
constwhere it shouldn’t be:The output stream is suppose to be non-const; after all, outputting data is changing something. So when you do this:
It cannot use the normal overload for
char*, because that one operates on a non-const stream. Instead, it searches for an appropriate overload and finds yours, determines it can construct anaClassfroma.message(because your constructor is notexplicit), does so, and calls it. This repeats forever.It should be written as: