Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Variable Type Selection at Runtime

Tags:

c++

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!

like image 316
user1259576 Avatar asked Dec 05 '25 19:12

user1259576


2 Answers

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).

like image 58
hmjd Avatar answered Dec 08 '25 11:12

hmjd


Use polymorphism with a common abstract base class, like this:

class HardwareBase
{
public:
    virtual void Open() = 0;
    virtual void Close() = 0;
    virtual ~HardwareBase() {};
};

Then derive your concrete hardware types:

class HardwareType1 : public HardwareBase
{
public:
    virtual void Open() {...}
    virtual void Close() {...}
};

And select the required hardware instance:

std::unique_ptr<HardwareBase> hw;  
if (userHwType == 1)  
    hw.reset(new HardwareType1());
else
    hw.reset(new HardwareType2());

// And use it like this:
hw->Open();

Note that you now need a pointer to the selected object instance. Use a unique_ptr to automatically delete it on exit.

like image 27
Gert-Jan de Vos Avatar answered Dec 08 '25 13:12

Gert-Jan de Vos



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!