Search code examples
c++userdefaults

Calling a virtual function on all classes inheriting from a given superclass


I'm trying to implement user defaults in my C++ app. For that I created an interface class with one function in it:

class IRegisterUserDefaults
{
public:
    IRegisterUserDefaults();
    virtual void registerUserDefaults(){}
};

Each class inheriting from this interface class will implement the function to register the user defaults it needs to be set.

So far no problem. But what's the best way of calling it? I'm coming from Objective-C where I could just search through all classes and find the ones who implement the interface and call the registerUserDefaults function on them. I understand though that C++ doesn't have this level of introspection. It would be sufficient to call the function once per class (and thus make it static).

Objective

It would be great if the function would be called "automatically" if a class subclasses IRegisterUserDefaults. I tried calling the method from the IRegisterUserDefaults constructor but it looks like this doesn't call the subclass function properly. Is there a way to make this happen?

Also, what would be best way to make sure this is only called once per class?


Solution

  • IRegisterUserDefaults is not a meaningful interface, in any language.

    It sounds like the actual problem you are trying to solve is "run some code once, at or near class first use". You can do that with something like this

    class HasUserDefaults {
        static std::once_flag register_once;
        void registerUserDefaults() { /*...*/ }
    public:
        HasUserDefaults ()
        { 
          // in all the constructors
            std::call_once(register_once, &HasUserDefaults::registerUserDefaults, this);
        }
    
        // other members
    };