2
#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?

thikonom
  • 4,219
  • 3
  • 26
  • 30
  • 1
    Why not just use `std::string`? – Karl Knechtel Jan 08 '11 at 22:11
  • Note that you're breaking the [rule of three](http://en.wikipedia.org/wiki/Rule_of_three_%28C%2B%2B_programming%29). If I copy your class, boom. You need a copy-constructor and assignment operator as well, use the [copy-and-swap idiom](http://stackoverflow.com/questions/3279543/what-is-the-copy-and-swap-idiom). Note that you should really just be using `std::vector` or `std::string`. – GManNickG Jan 08 '11 at 22:11

1 Answers1

11

Because you have const where it shouldn't be:

/////                     /////
const ostream& operator<<(const ostream& o, const aClass &a)

The output stream is suppose to be non-const; after all, outputting data is changing something. So when you do this:

o << a.message;

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 an aClass from a.message (because your constructor is not explicit), does so, and calls it. This repeats forever.

It should be written as:

ostream& operator<<(ostream& o, const aClass &a)
{
    o << a.message;
    return o;
}
GManNickG
  • 494,350
  • 52
  • 494
  • 543
  • 1
    And make the constructor `explicit` while you're at it. Or better yet, **just use `std::string`**! – Karl Knechtel Jan 08 '11 at 22:12
  • Aside from this, aClass is fragile (it doesn't have private copy-constructors & assignment operatorts) and inefficient (the result of strlen should be stored to a local then memcpy should be used in place ot strcpy). – Achille Jan 08 '11 at 22:13