Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Always call superclass virtual function when child override is called

Tags:

c++

I have this structure:

class A
{
public:
    virtual void func(int a)
    {
        cout << "System is initiated correctly." << a;
    }
};

class B : public A
{
public:
    virtual void func(int a) override
    {
        A::func(a);
        cout << "This particular system is initiated correctly too" << a;
    }
};

Now in 95% cases when I sublcass from A I override func and in 100% of those cases I should call A::func(); before doing anything else? How can I prevent writing this manually. Sometimes I even forget in child class to call A::func(); and get runtime errors, throws and so on.

like image 769
Narek Avatar asked Feb 13 '15 11:02

Narek


1 Answers

How about the NVI pattern?

class A
{
public:
    void func(int a)
    {
        cout << "System is initiated correctly." << a;
        do_func(a);
    }

private:
    virtual void do_func(int a) {}
};

class B : public A
{
private:
    virtual void do_func(int a) override
    {
        cout << "This particular system is initiated correctly too" << a;
    }
};
like image 148
T.C. Avatar answered Nov 15 '22 04:11

T.C.