Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copy constructor between derived classes

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?

like image 863
cozos Avatar asked Dec 22 '25 22:12

cozos


1 Answers

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.

class Player
{ 
public:
    friend class Human;    // These friends are necessary if the controllers
    friend class Computer; // need access to Player's private data.

    Card hand[4];
    Controller* controller;
};

class Controller
{
public:
    virtual Command getCommand(Player const&) = 0;
};

class Human : public Controller
{
public:
    Command getCommand(Player const&) { /* get command from user input */ }
};

class Computer : public Controller
{
public:
    Command getCommand(Player const&) { /* get command from AI */ }
};

Then, when you need to switch from Human to Computer, just change the controller.

p1->controller = new Computer();

This way, the cards will be maintained, only the control mechanism will be changed.

like image 108
Peter Alexander Avatar answered Dec 24 '25 13:12

Peter Alexander



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!