Search code examples
c++oopmultiple-inheritance

Pass parent class reference as argument in derived class in C++


I'm new to C++ and am trying to achieve the following design.

class A { do (); doMore (); } // abstract
class B { do (); doMore (); } // abstract

class X : public A, public B // Also abstract
{        
    foo() {
        // common code
        A::do();
        A::doMore();
    }
    bar() {
        // common code
        B::do();
        B::doMore();
    }
}

Both A and B provide implementations of do() and doMore(). How can I extract the common code that the new function takes an arg that calls the method in the correct parent class?

Something like

X::newMethod(arg_that_indicates_parent_class) {
    // common code
    arg_that_indicates_parent_class::do();
    arg_that_indicates_parent_class::doMore();
}

Then call it like so

newMethod(pass_A_somehow);
newMethod(pass_B_somehow);

Looks like runtime polymorphism, but not quite (or is it?)... as it is within a child class...

Is this design itself just trash and there is a better way to achieve this?


Solution

  • If the idea is that do and doMore will be present in both A and B and those are the functions specifically you wish to call, you could use a template function like so:

    class X : public A, public B // Also abstract
    {        
        template <typename T>
        void newMethod()
        {
            T::do();
            T::doMore();
        }
    }
    

    Then using it explicitly, you could then do it like so:

    X x;
    x.newMethod<A>();
    x.newMethod<B>();
    

    This has the added benefit of catching some errors at compile time, that is, if you try and pass a C and it does not have the do and doMore functions defined, you will receive a complier error (instead of a run-time crash).

    This also lets you utilize the std::enable_if functionality if you are using C++1x.

    Hope that can help.