Jeff Gong Jeff Gong - 3 months ago 15
C++ Question

Retrieve specific string based on subclass

I have a bunch of different subclasses of one class called Strategy, each of which has a unique string identifier

class AdaptiveStrategy : Strategy {
public:
const static std::string uniqueKey;

AdaptiveStrategy();
private:
...
}


Each of these in the .cpp file has a unique identifier based on its name. I also have another .cpp file managing these strategies. This Selector class has a pointer to a Strategy, of which can change during the duration of my project.

class Selector {
public:
Selector()
std::string getStrategyName() // help!

private:
Strategy *currentStrategy // can be any of the viable Strategy subclasses
}


Essentially this pointer is repeatedly replaced to point at new Strategies based on a bunch of different things that may happen.

I'd like in this Selector class to have some way of returning the current active Strategy's unique string identifier -- what would be the best way of doing this?

Answer

Typically, this is done by declaring a pure virtual method in the base class (let's say the method's name is 'toString'). Then all derived classes have to implement the toString-method.

Another way to do this is to store the name in the base class. Therefore you've to overload the constructor and to pass the name of the derived class to the parent constructor.

class AdaptiveStrategy : Strategy {
...
  AdaptiveStrategy() : Strategy("AdaptiveStrategy") { }
...
};
Comments