How do you copy a derived class to another?
I’m terminologically deficient, so I’ll try to illustrate with an example.
We are playing a card game with a computer player and human player. Card and Command are other classes.
class Player
{
Card *Hand[4];
// etc...
};
class Human: public Player
{
Command getCommand();
void PlayCard(Card card);
void quit();
// etc...
};
class Computer: public Player
{
Command ai();
void PlayCard(Card card);
// etc...
};
And somewhere in the main function we have …
// ...
Human p1; // Assume initialized and usable.
if(p1.getCommand() == QUIT)
{
cout << "PLAYER 1 RAGEQUITS WHAT A NOOB LOL << endl;
cout << "A COMPUTER WILL NOW TAKE OVER." << endl;
p1.quit()
p1 = new Computer(); // THE IDEA BEING THAT WE WANT TO PRESERVE p1's MEMBERS.
}
// ...
What I am trying to do is converting p1 to a “Computer” while preserving the state of its members.
Do we use a copy constructor to do this? If not, what methods do you use?
EDIT: Is this the way to use the assignment operator?
Computer& Human::operator=(const Human &h) // Assignment operator
{
Hand = h.Hand;
member2 = h.member2;
member3 = h.member3;
...
return *this;
}
Do we need to delete/free anything in the main?
You have a design problem here. If you want to switch a player from a Human to a Computer while maintaining the common member variables then you should structure your classes in that way.
Then, when you need to switch from Human to Computer, just change the controller.
This way, the cards will be maintained, only the control mechanism will be changed.