jeudi 22 juillet 2021

How to make sure overridden function is called

Is there some way that I can make sure that the base classes function is called from the overridden function in the child class.

Example:

#include <iostream>

class Base
{
public:
    virtual void func()
    {
        std::cout << "Really important code was ran" << std::endl;
    }
};

class ChildExplicit : public Base
{
    void func() override
    {
        Base::func();
        std::cout << "child class explicitly calling Base::func" << std::endl;
    }
};

class ChildImplicit : public Base
{
    void func() override
    {
        std::cout << "child not explicitly calling Base::func" << std::endl;
    }
};

int main()
{
    Base* explicitChild = new ChildExplicit();
    Base* implicitChild = new ChildImplicit();
    explicitChild->func();
    std::cout << std::endl;
    implicitChild->func();
}

This should either output this:

Really important code was ran
child class explicitly calling Base::func

Really important code was ran
child not explicitly calling Base::func

or yield some kind of error that Base::func was not called in ChildImplicit::func.

One solution that would be possible is to make func non virtual and creating a second protected function that will be called in Base::func, the child classes would then override the protected function. But as you can imagine if apply this to a Base class of the Base class of the Base class scenario and each of there implementations must be called this gets quite messy. Would there be an other way to achieve the same goal?

Aucun commentaire:

Enregistrer un commentaire