jeudi 31 août 2017

Simulate constructor behaviour for virtual methods

I am currently working on a small private project using C++ i came up with the following structure:

#include <iostream>

class A
{
    std::vector<int> vec;

protected:
    virtual bool onAdd(int toAdd) {
        // should the 'adding' be suppressed?
        // do some A specific checks
        std::cout << "A::onAdd()" << std::endl;
        return false; 
    }

public:
    void add(int i) {
        if(!onAdd(i)) {
            // actual logic
            vec.push_back(i);
        }
    }
};

class B : public A
{
protected:
    bool onAdd(int toAdd) override {
        // do some B specific checks
        std::cout << "B::onAdd()" << std::endl;
        return false;
    }
};

In this example onAdd is basically meant to be a callback for add, but in a more polymorphic way.

The actual problem arises when a class C inherits from B and wants to override onAdd too. In this case the implementation in B will get discarded (i.e. not called) when calling C::add. So basically what I would like to achieve is a constructor-like behaviour where I am able to override the same method in different positions in the class hierarchy and all of those getting called.

My question now is: Is there a possibility/design to achieve this? I am sure that it wouldn't be as easy as cascading constructors, though.

Note: Don't focus too much on the add example. The question is about the callback like structure and not if it makes sense with an add.

Aucun commentaire:

Enregistrer un commentaire