C++ Variable Type Selection at Runtime

c++

Solution

Create an an abstract base class, and derive two concrete classes from it: one implementing type1 and the other implementing type2:

class Hardware
{
public:
    virtual ~Hardware() {};
    virtual void doSomething() = 0;
};

class Hardware1: public Hardware
{
public:
    void doSomething() { // hardware type1 stuff. }
};


class Hardware2: public Hardware
{
public:
    void doSomething() { // hardware type2 stuff. }
};

Then create the necessary instance:

std::unique_ptr<Hardware> hardware(1 == userHwType ? new Hardware1() : 
                                                     new Hardware2());

hardware->doSomething();

If you compiler does not support C++11 then `std::unique_ptr` will not be available to you. An alternative smart pointer would `boost::scoped_ptr` (or `boost::shared_ptr`).

Problem

I am upgrading an old application which was written for a specific hardware interface. I now need to add support for a modern hardware to the existing application. To do this, I would like to create a class for each hardware type, and assign a variable to one type or the other whenever the user selects which hardware is in their system. For example: Class `HardwareType1` and Class `HardwareType2` both exist having the same member functions. ``` object HW; if (userHwType = 1) // initialize HW as a HardwareType1 class } else{ // initialize HW as a HardwareType2 class } ``` Now I can use `HW.doSomething()` throughout my code without a conditional for hardware type every time I interact with the hardware. I'm sure this is pretty basic but to be honest I don't even know what this is called or what terms to search on for this one. Thanks!

Original source