In our system, we have
- multiple deviceTypes
- each deviceType can have a different configuration type
- each deviceType will be a library of its own
I'm in a situation where I am forced to use dynamic_cast. I'm wondering if there is a better way to design this ?
what I have is:
// in common code
class Config {public: virtual ~Config(){} };
class Device {
protected:
Config* devConfig;
protected:
virtual void createDevConfig() = 0;
public:
virtual void display() = 0;
};
// Device specific Code
class A0Device : public Device {
protected:
virtual void createDevConfig() { this->devConfig = new A0Config(); }
public:
A0Device() { this->createDevConfig(); }
virtual void display(){
A0Config* config = dynamic_cast<A0Config*>(this->devConfig);
if(!config) std::cout << "Null object\n";
}
};
class A0Config : public Config {};
int main() {
Device* dev = new A0Device();
dev->display();
return 0;
}
Essentially A0Device has its own config type: A0Config, which is composed of other members. A0Device has devConfig defined as Config* in base class. In A0Device::display() - I need to access the devConfig object (as A0Config type). The virtual createDevConfig() ensures the config object will always be of type A0Config in A0Device => Is it safe to use dynamic_cast here ? Is there a better way of designing this ?