I want to choose the implementation of an abstract class based on settings from a config file. Is this the proper way of doing that?
I am asking because I am having doubts about using std::make_unique inside the if scope. Will the object created with std::make_unique still be valid outside of the if scope?
#include <iostream>
#include <memory>
// Base class for all position systems
class PositionSystem {
public:
virtual int getX() const = 0;
};
// GPS implementation
class GPS: public PositionSystem {
public:
int getX() const {return 42;};
};
// Galileo implementation
class Galileo: public PositionSystem {
public:
int getX() const {return 21;};
};
int main(){
// Settings are read from config file
// and stored in a smiliar struct
struct {std::string position_system = "Galileo";} settings;
// Declare position system
std::unique_ptr<PositionSystem> ps;
// Choose implementation based on settings
if(settings.position_system == "GPS"){
ps = std::make_unique<GPS>(GPS());
}
else if (settings.position_system == "Galileo"){
ps = std::make_unique<Galileo>(Galileo());
}
// Use interface
std::cout << ps->getX() << '\n';
return 0;
}