jeudi 2 juillet 2020

How can one force an overriden methods base method to be called from the overriden method?

I have an class:

class MyCoolBean {

public:

    virtual void toot(){
        log("ooh la la");
    }
}

And my derived class:

class MyCoolBeansBoy : public MyCoolBean{
public:
    void toot()override{
        log("oh yeah");
    }
}

If I do:

MyCoolBeansBoy boi; boi.toot();

The output is:

oh yeah

But I want the output to be:

ooh la la
oh yeah

Now I know I can modify the derived function to be:

    void toot()override{
        MyCoolBean::toot();
        log("oh yeah");
    }

But if I do that, then anyone implementing a derived class can simply forget. Is there anyway to force MyCoolBean::toot() to be called ?

EDIT: I know this is technically possible because of this questions answers:

How to ensure that every method of a class calls some other method first?

The solution in the above link can be used to force calling a member function by all functions! My question is how to do it only for an overriden method, and call specifically the base method! :)

Aucun commentaire:

Enregistrer un commentaire