mercredi 22 août 2018

c++ base class called but returning derived class

Before all, I am tied to C++98, how I wish our supplier (and their supplier) would update

I am working with a 3rd party framework from which I do have sources. I do not want to change the sources to make sure I am upwards and downwards compatible.

That framework has a base class Channel and derived classes Digital and Analog

class Channel
{
    getChannel(std::string chName)
    {
        //returns a Channel  
    }
    bool IsDigital()
    {
       //returns true for digital otherwise false
    }
}

class Digital : public Channel
{
    // functionality for Digital
}

class Analog : public Channel
{
    // functionality for Analog
}

The base class allows me to find a 'Channel' by calling the getChannel(std::string chName) method. the base class also has a method IsDigital(). That method returns true when the channel is Digital otherwise it is Analog.

Is there a way (or pattern) that I can use to request the channel from the base class and get returned a Digital or Analog (derived class) ? If I need to build classes in between to get it done it is ok for me. I would like to prevent from loads of getting channels in the program and casting them and ending up with multiple variables bla bla

Digital* d;
Analog*  a;
Channel* c;

c = framework->getChannel("name");
if (c->IsDigital())
{
   d = dynamic_cast<Digital>(c);       
}
else
{
   a = dynamic_cast<Analog>(c);       
}

I hope there is something possible like

MyInBetweenClass* helper;
MyOwnClass *io;

io = helper(framework->getChannel("name"));

where helper gets the Channel as input and returns a Digital or Analog

Aucun commentaire:

Enregistrer un commentaire