1

considering following code:

#include <stdio.h>
struct ITimer {
    virtual void createTimer() = 0;
};
class A : public ITimer
{
    public:
        void showA() {
            printf("showA\n");
            createTimer();
        }
};

class B : public ITimer
{
    public:
        void showB() {
            printf("showB\n");
        }
        void createTimer() {
            printf("createTimer");
        }
};

class C: public A, public B
{
    public:
        void test() {
            showA();
            showB();
        }
};

int main()
{
    C c;
    c.test();
    return 0;
}

I need to use interface ITimer in class A, but the method is implemented in class B. So I inherited the interface in A, but the compiler is not happy with it:

test.cc
test.cc(38) : error C2259: 'C' : cannot instantiate abstract class
        due to following members:
        'void ITimer::createTimer(void)' : is abstract
        test.cc(5) : see declaration of 'ITimer::createTimer'

How could I use the interface in baseclass A while its method is implemented in class B.

Thanks.

Jichao
  • 40,341
  • 47
  • 125
  • 198

1 Answers1

4

Inheritance is the base-class of all evil.

A nor B are ITimers

A doesn't even implement the pure virtual, so it cannot be instantiated. Therefore, inheriting from A makes C abstract too (cannot be instantiated).

You don't want to use inheritance here. See


In this case, the dreaded diamond-of-death hierarchy could be fixed by adding virtual:

class A : public virtual ITimer
//...
class B : public virtual ITimer

See it Live on IdeOne. I don't recommend this, though. Consider fixing the design.

See also Diamond inheritance (C++)

Community
  • 1
  • 1
sehe
  • 374,641
  • 47
  • 450
  • 633