I recently had the weirdest problem in my C++ codebase. Hopefully someone can confirm and/or clear up my understanding here:
First, I have the two classes in question. They are like this:
class Physical {
//... code
enum update {UPDATE_POS};
virtual void Update(update u)=0;
};
class Character : public Physical, public std::iostream {
//... code
virtual void Update(update u);
};
So those are my two classes.
Now, in my MUD, I have a coordinate-based system. I was in the process of implementing movement. Players (and other things) move at a given velocity, hence the Update function handles the distance they have moved in s seconds (where s is the number of seconds since Update was last called).
Now, before I fixed my problem, I had code like this:
void Character::Update(update u)
{
//Code to decipher the constant requested
*this << "You have finished moving." << sendl;
//sendl is similar to std::endl, but it puts "\r\n" on the
//character stream rather than just "\n"
//Rest of the code
}The code would compile and run. However, the odd part was that I wasn't getting the string to show up on the screen. It was showing an integer which looked like a pointer value. What was even odder was that I could print out integer and floating-point constants with no problem. When I tried wrapping the string with a std::string, the compilation would fail.
After pounding my head a bit, I did this:
void Character::Update(update u)
{
//Code again
*static_cast(this) << "You have finished moving." << sendl;
}
This compiled and worked as expected.
Frankly, I'm baffled by this. I haven't gone to my C++ standard yet to see the offical reason, but I think this is what was happening:
The Update function is in the Physical class, so the this pointer in the Update function acts more like a Physical* object rather than a std::iostream* or even a Character* object. The function lookup mechanism, therefore, doesn't look up out-of-class functions such as operator<<(const char*) or operator<<(std::string).
Is this understanding correct?