vendredi 7 octobre 2016

How to create a polymorphic and additive init() function in C++?

Suppose there is a simple hierarchy without multiple inheritance involved:

class base {
public:
    base() { /* */ }
    virtual void init() { /* */ }
};

class derived_a : public base {
public:
    derived_a() { /* */ }
    virtual void init() override { base::init(); /* local stuff to add */ }
};

class derived_b : public base {
public:
    derived_b() { /* */ }
    virtual void init() override { base::init(); /* local stuff to add */ }
};

Then the client code goes like

auto d_a = new derived_a{};
d_a->init();

I see two problems:

a) Repeating base::init() in every derived_x::init()

b) Repeating derived_x::init() every time a derived class object is created

Both can easily be forgotten, from my point of view.

I know that in base::base{}, you're base, not derived_x, by how virtual dispatch works in C++. But there is be a workaround, isn't there? Looks like a common problem that developers have faced many times already. What is (are) the possible solution(s)?

Aucun commentaire:

Enregistrer un commentaire