user3508551 user3508551 - 1 year ago 64
C++ Question

What is the best programming practice to simulate an evolved class?

Suppose I have two classes:

class SwordsMan{
virtual SwordsMan* evolve()

class Warrior: public SwordsMan{

What I am trying to aim for is that the SwordsMan evolves into a Warrior once he has enough experience. What would be the best practice to do for implementing this evolve() function given that I want to delete the "this" SwordsMan object once he evolves?

Answer Source

It's generally a better idea to separate the objects' implementation from the management of their lifetime.

class SwordsMan {
  virtual std::unique_ptr<SwordsMan> evolve();

class Warrior: public SwordsMan { };

In the class one layer above, the code could look like this:

auto swordsMan = std::make_unique<SwordsMan>(); // Get a swordsman

if(auto evolved = swordsMan->evolve()) // Ask him to evolve
    swordsMan = std::move(evolved); // Replace him

If you only call evolve() when you definitely want to upgrade the swordsman, you can drop the if:

swordsMan = swordsMan->evolve();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download