Vorac
Vorac

Reputation: 9114

Is it possible to implement an interface through inheritance?

struct I { 
      virtual void foo() = 0; 
      virtual void bar() = 0;
};

struct A { 
        void foo(){};
 };
struct B: public A, public I {

     void bar(){};
};

Is this pseudo-code supposed to be valid in C++? Currently I am getting an undefined reference error for foo() at link time.

If this is not supposed to work, please recommend a technique to create an interface, which gets implemented by inheritance, as in the example.

Upvotes: 1

Views: 90

Answers (2)

Danish Rizvi
Danish Rizvi

Reputation: 91

  1. virtual functions cannot be inlined. You are inlining A::foo() and B:bar()
  2. You are inheriting I from two paths in class B. Through A and directly through I. You will need to provide the implementation of foo() in class B as well.

Upvotes: -1

Mike Seymour
Mike Seymour

Reputation: 254471

It depends what you mean by "valid". You'll have to add the missing return types, and perhaps fix some other syntactic issues, to get it to compile.

If you mean, "is B a non-abstract class that correctly overrides both pure virtual functions declared in I?", then no. It doesn't override foo; inheriting a function of the same name does not count as overriding.

If you want A::foo to be the implementation of I::foo, then you'll have to add a wrapper in B to provide the override:

void foo() {A::foo();}  // assuming the missing return type is void

Upvotes: 5

Related Questions