mardi 1 septembre 2020

best way to inherit from a class without virtual functions

I am trying to implement some event handling. There are different types of events: integerChangedEvent, boolChangedEvent, stringChangedEvent and so on... Each of these events hold some of the same information like: std::string settingsName, std::string containerName... But also each of these different event types also hold some information which are unique for this event types: e.g. int double std::string... newValue and oldValue.

My idea to not copy the same code thousands of times is to make a base class called SettingsEvent. This class should hold the information which all event types also would hold and which are same (see above "settingsName, containerName") and of cause the setter and getter of these information.

All other events can inherit this base class and add their own members / methods.

so far, everything is fine.

But C++ (11) does not allow me to inherit from a class without at least one method which is virtual. But I don't want to allow, that any of these methods are overwrite able. What can I do? Is there a specifier which allows me to inherit a non-virtual class?

for better understanding, here is some piece of code:

class SettingsEvent
{
public:
    std::string getSettingsName() const;
    std::string getSettingsContainerName() const;
    // some more methods I don't want to write down know... ;)
protected:
    SettingsEvent(); //protected constructor, to ensure nobody creates an object of this base class
private:
    std::string m_settingsName;
    std::string m_settingsContainerName;
    // some more members I also don't want to write down know...
};

class IntegerChangedEvent : public SettingsEvent
{
public:
    IntegerChangedEvent(); //public constructor, it is allowed to create an object of this class
    int getNewValue() const;
    int getOldValue() const;
    //also here are more methods I don't want to list
private:
    int m_newValue;
    int m_oldValue;
    //also more members I don't want to list
};

On another part in my code I want to pass the event to a method. In that method I want to cast it into the IntegerChangedEvent:

void handleEvent(SettingsEvent* event)
{
    //to be honest, the event itself knows what kind of event it is (enum) but lets say it is an IntegerChangedEvent to keep it simple
    IntegerChangedEvent* intEvent = dynamic_cast<IntegerChangedEvent*>(event);
   
    if(intEvent)
    {
        //do stuff
    }
}

the error message is: "C2683: 'dynamic_cast': 'SettingsEvent' is not a polymorphic type

Aucun commentaire:

Enregistrer un commentaire