2

I'm looking for a clean way of doing this since a long time. In my problem, there exist 3 classes not sharing any parent in common but each having some methods with the same name (A.doSomething, B.doSomething, C.doSomething). Hence, having the same function signature, class D inheriting from A and using method doSomething() will "look the same" to E inheriting from B or C .

Here is a sketch of what I'd like to be able to do:

class Base {
    public:
    void myMethod(void) { doSomething(); }
};

class Independent {
    public:
        doSomething();
};

clase Derived : public Base : public Independent {
 (...)
};

int main(void) {
   Derived *derivedObject = new Derived();
   derivedObject->myMethod();
}

In this problem, object of type "Independent" is provided by a library that I cannot change. I would like to define a base class that uses methods that are going to be inherited later on. I couldn't find a proper way of doing this using virtual inheritance without causing ambiguous compiling.

1
  • Can you explain your problem a little more clearly? I only see one method called "doSomething" in that code snippet, but you mention three classes that have it in the description, and you make no comment on what the "myMethod" method is supposed to be for. Commented Jun 18, 2009 at 2:57

1 Answer 1

5

You've got a nasty situation there. One solution to this would be using the Curiously Recurring Template Pattern to perform the inheritance at compile-time, like this:

template <typename D>
class Base {
    public:
        void myMethod(void) { static_cast<D*>(this)->doSomething(); }
};

class Independent {
    public:
        void doSomething();
};

clase Derived : public Base : public Independent {
    /*...*/
};

int main(void) {
   Derived *derivedObject = new Derived();
   derivedObject->myMethod();
}

Alternatively, you could choose to put a middleman class in between to forward to Independent (I assume you have many classes deriving from the same Base and Independent, and just don't want to have to do this for each class).

template <typename D>
class Base {
    private:
        virtual void doSomethingImpl();
    public:
        void myMethod(void) { doSomethingImpl(); }
};

class Independent {
    public:
        void doSomething();
};

class IndependentWrapper : public Base : public Independent {
    private:
        void doSomethingImpl() { Independent::doSomething(); }
};

clase Derived : public IndependentWrapper {
    /*...*/
};

int main(void) {
   Derived *derivedObject = new Derived();
   derivedObject->myMethod();
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.