Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: using a base class as the implementation of an interface

In C++ is it possible to use another base class to provide the implementation of an interface (i.e. abstract base class) in a derived class?

class Base {     virtual void myfunction() {/*...*/}; } class Interface {     virtual void myfunction() = 0; } class Derived     : public Base, public Interface {     // myfunction is implemented by base } 

The above should compile, but doesn't actually work. Is there any way to achieve this effect?

In case anyone cares, the reason for wanting this is that it make sense (for my application) to use a generic library from another project/namespace to provide the implementation of an interface in my project. I could just wrap everything, but that seems like a lot of extra overhead.

Thanks.

like image 576
deuberger Avatar asked Sep 10 '10 16:09

deuberger


People also ask

Can a base class implement an interface?

A base class can also implement interface members by using virtual members. In that case, a derived class can change the interface behavior by overriding the virtual members.

What is base class in interface?

Base classes. Allows you to add some default implementation that you get for free by derivation (From C# 8.0 by interface you can have default implementation) Except C++, you can only derive from one class. Even if could from multiple classes, it is usually a bad idea. Changing the base class is relatively easy.

What must class do to implement an interface?

A class that implements an interface must implement all the methods declared in the interface. The methods must have the exact same signature (name + parameters) as declared in the interface. The class does not need to implement (declare) the variables of an interface. Only the methods.

What is base class in C?

A base class is a class, in an object-oriented programming language, from which other classes are derived. It facilitates the creation of other classes that can reuse the code implicitly inherited from the base class (except constructors and destructors).


1 Answers

If Base isn't derived from Interface, then you'll have to have forwarding calls in Derived. It's only "overhead" in the sense that you have to write extra code. I suspect the optimizer will make it as efficient as if your original idea had worked.

class Interface {     public:         virtual void myfunction() = 0; };  class Base {     public:         virtual void myfunction() {/*...*/} };  class Derived : public Interface, public Base {     public:         void myfunction() { Base::myfunction(); }  // forwarding call };  int main() {    Derived d;    d.myfunction();    return 0; } 
like image 198
Adrian McCarthy Avatar answered Oct 14 '22 05:10

Adrian McCarthy