Home > Enterprise >  How to require child class method to call parent class method?
How to require child class method to call parent class method?

Time:02-13

Let's say I have a parent class A.

class A
{
    public:
        A() {}

        void MyMethod()
        {
            printf( "A\n" );
        }
};

And I have a child class B.

class B : public A
{
    public:
        B() {}

        void MyMethod()
        {
            printf( "B\n" );
        }
};

Now, I would like to require class B to call A::MyMethod(), without explicitly calling it, as shown above. Resulting in:

A
B

Or

B
A

Would that be possible?

Right now B->MyMethod() only calls the child method.

CodePudding user response:

Non-Virtual Interface idiom has the base class define a public non-virtual member function, and a private virtual member function that is an override point for derived classes.

The public non-virtual member function acts as a public facing API.

The private virtual member function acts as a class hierarchy facing API.

Separating those two concerns can be a handy technique especially for larger projects, and for debugging purposes, and for ensuring pre- and post- operations in the base class's public non-virtual member function.

#include <iostream>

using std::cout;

namespace {

class A {
    virtual void MyMethodImpl() const {
        // Derived classes should override this virtual member function
        // and add their extra steps there.
    }
public:
    virtual ~A() = default;
    A() {}

    void MyMethod() const {
        cout << "A::MyMethod before steps.\n";
        MyMethodImpl();
        cout << "A::MyMethod after steps.\n";
    }
};

class B : public A {
    void MyMethodImpl() const override {
        cout << "B::MyMethodImpl extra steps.\n";
    }
public:
    B() {}
};

} // anon

int main() {
    B b;
    b.MyMethod();
}

CodePudding user response:

There's no way to require one class method to call another one, in C , except for the requirement that a constructor and a destructor in a derived class must call the parent class's, in specific ways.

Except for that, there is no way to directly require this, in C .

  • Related