I'm not seeing anywhere you construct my_player
, so I have a feeling that some of the code is missing. Specifically, I think your constructor has this line:
my_player = new fooPlayer()
A fooPlayer
object is not quite the same thing as an auto_ptr<fooPlayer>
object, and auto_ptr
is intentionally designed to prevent assigning from one to the other because, frankly, the alternative is worse. For the details, look up (1) conversion constructors, (2) the explicit
keyword, and (3) copy constructors and destructive copy semantics.
You should change the constructor to either:
class fooPlayerFactory {
public:
fooPlayerFactory()
{
my_player = std::auto_ptr<fooPlayer>(new fooPlayer());
}
Or (using a member initializer list):
class fooPlayerFactory {
public:
fooPlayerFactory() : my_player(std::auto_ptr<fooPlayer>(new fooPlayer()) { }
The solution isn't pretty but, like I said, the alternative is worse due to some really arcane details.
As a bit of advice, though, you're making life harder than it needs to be; and may in fact be causing strange bugs. auto_ptr
exists to manage the lifetime of an object, but the only reason you need to worry about the lifetime of my_player
is that you've allocated it with new
. But there's no need to call new
, and in fact there's no need to keep my_player
. And unless fooPlayerFactory
is meant to be the base class for some other factory, there's no need to mark functions virtual
.
Originally I thought you could get away with simply returning copies of the my_player
object, but there's a problem: before returning my_player
from MakePlayer()
you call a method on it, and I assume that method changes the internal state of my_player
. Further calls to MakePlayer()
will change the state again, and I think you're going to eventually have my_player
in the wrong state. Instead, return a different fooPlayer
object with each request. Don't do memory management, just promise to construct the object. That way the user can decide on memory allocation:
fooPlayerFaclotry factory;
fooPlayer on_stack = factory.MakePlayerX();
fooPlayer* on_heap_raw_pointer = new fooPlayer(factory.MakePlayerO());
std::auto_ptr<fooPlayer> on_heap_managed_scope
= std::auto_ptr<fooPlayer>(factory.MakePlayerX());
I would change fooPlayerFactory
to look like this:
class fooPlayerFactory
{
private:
fooPlayer MakePlayer(const char letter) const
{
fooPlayer result;
result.fooPlayerfunc();
return result;
}
public:
fooPlayer* MakePlayerX() const
{
char go_first = askYesNo("Do you require the first move?");
return MakePlayer(go_first);
}
fooPlayer MakePlayerO() const
{
return fooPlayer();
}
};