5

I would like to use interfaces in c++ like in java or in c#. I decided to use purely abstract classes with multiple inheritance, but something is terribly wrong when I specialize the interface:

class Interface
{
public:
  virtual int method() = 0;
};

// Default implementation.
class Base: virtual public Interface
{
public:
  virtual int method() {return 27;}
};

// specialized interface
class Interface2: public Interface
{
public:
  virtual int method() = 0;
// some other methods here
};


// concrete class - not specialised - OK
class Class: public virtual Interface, public virtual Base
{
};

// concrete class - specialised
class Class2: public Interface2, public Base
{
};



int main()
{
  Class c;
  Class2 c2;
return 0;
}

Warning 1 warning C4250: 'Class' : inherits 'Base::Base::method' via dominance 30

Error 2 error C2259: 'Class2' : cannot instantiate abstract class 42

What is the proper way to do this?

14
  • 1
    Why do you not use virtual inheritance for Class2?
    – anon
    Apr 30, 2009 at 12:07
  • 2
    Another question is why are you trying to reimplement Java in C++?
    – jalf
    Apr 30, 2009 at 12:11
  • What exactly are you trying to do? Do you want mixins, where methods in one base class can call methods in another base class, or just "regular" multiple inheritance? If the latter, why use virtual inheritance, and why inherit from both Interface and Base (the latter is sufficient)? Apr 30, 2009 at 12:11
  • To be clear: please describe exactly the behaviour you expect for Class and Class2 (e.g. what should happen when method() is called; can a pointer/reference to Interface2 be used to point to an instance). Apr 30, 2009 at 12:13
  • If the method is not reimplemented in Class2 or Class (it is not in this case) Base::method() will be called. Otherwise the reimplementation will be called. There is an interface hierarchy with a common base dumb implementation.
    – danatel
    Apr 30, 2009 at 12:32

7 Answers 7

5

Class2 inherits from an abstract class (Interface2) but does not implement the pure virtual method, so it remains as an abstract class.

5
  • The method is implemented in Base. Base brings default implementation. Interface2 is specialized Interface. Imagine Interface = Protocol, Interface= TCP/IP protocol, Base - contains support methods. Class is an http server.
    – danatel
    Apr 30, 2009 at 12:19
  • 1
    Yes, but it is not implemented in Interface2. If they do different things, then they probably shoudn't have the same name.
    – Tom
    Apr 30, 2009 at 12:27
  • Interface never implements anything. It is just a statement that certain methods are available. For example Interface can do method(), method2() and method3(). Interface2 brings method4() and method5(). There may be many implementations of both Interface and Interface2. Base usually contains trivial operations which can be reused by the whole hierarchy.
    – danatel
    Apr 30, 2009 at 12:41
  • 1
    @danatel, Tom means that the implementation Base::method() is not automatically "used" by Class2 as an implementation of Interface2::method(), so you need some extra syntax to have this effect. This is probably so to avoid accidental interface... sorry, pure abstract class... method implementations due to random name clashes caused by inheriting from another concrete class. Apr 30, 2009 at 13:32
  • Agree. So far it looks like this is impossible to do in c++. See Pieters answer and j_random_hackers comments.
    – danatel
    Apr 30, 2009 at 18:43
4

Heh heh, this problem tickles something buried deep in my head somewhere. I can't quite put my finger on it but I think it's to do with defining an interface heirarchy and then inheriting both an interface and an implementation. You then avoid having to implement all functions with by forwarding calls to a base class. I think.

I think this simple example shows the same thing, but is maybe a bit easier to understand because it uses things that can be easily visualized: (please forgive the struct laziness)

#include <iostream>
using namespace std;

struct Vehicle
{
    virtual void Drive() = 0;
};

struct VehicleImp : virtual public Vehicle
{
    virtual void Drive() 
    {
        cout << "VehicleImp::Drive\n";
    }
};

struct Tank : virtual public Vehicle
{ 
    virtual void RotateTurret() = 0;
};

struct TankImp : public Tank, public VehicleImp
{
    virtual void RotateTurret() 
    {
        cout << "TankImp::RotateTurret\n";
    }
    // Could override Drive if we wanted
};

int _tmain(int argc, _TCHAR* argv[])
{
    TankImp myTank;
    myTank.Drive();         // VehicleImp::Drive
    myTank.RotateTurret();  // TankImp::RotateTurret
    return 0;
}

TankImp has essentially inherited the Tank interface and the Vehicle implementation.

Now, I'm pretty sure this is a well known and acceptable thing in OO circles (but I don't know if it has a fancy name), so the dreaded diamond thing is ok in this case, and you can safely suppress the dominance warning because it's what you want to happen in this case.

Hope that somehow helps point you in the right direction!

BTW, your code didn't compile because you hadn't implemented the pure virtual "method" in Class2.

EDIT:

Ok I think I understand your problem better now and I think the mistake is in Interface2. Try changing it to this:

// specialized interface
class Interface2: public virtual Interface // ADDED VIRTUAL
{
public:
    //virtual int method() = 0;   COMMENTED THIS OUT
    // some other methods here
};

Interface2 should not have the pure virtual defintion of method, since that is already in Interface.

The inheritance of Interface needs to be virtual otherwise you will have an ambiguity with Base::method when you derive from Interface2 and Base in Class2.

Now you should find it will compile, possibly with dominance warnings, and when you call c2.method(), you get 27.

3
  • Yes, the point is that I do not want to implement the method in class2. I want to inherit the base implementation. Your example is unfortunatelly unrelated to my situation.
    – danatel
    Apr 30, 2009 at 18:36
  • Bingo! This is the answer I was looking for! Conclusion: using virtual inheritance does allow methods to be "blended" in C++. danatel: Please mark this as the accepted answer. May 1, 2009 at 2:52
  • 1
    To summarise: the problem is that there are two distinct Interface subobjects in the definition of Class2 as it stands -- one from Base, one from Interface2. Making Interface2 inherit virtually from Interface collapses these two subobjects into one, eliminating the ambiguity of calling "Interface::method()". May 1, 2009 at 3:02
4

Based on this comment

If the method is not reimplemented in Class2 or Class (it is not in 
this case) Base::method() will be called. Otherwise the reimplementation 
will be called. There is an interface hierarchy with a common base 
dumb implementation. 

– danatel 16 mins ago

That's not what you got, you don't have a common base, you've got

Interface -> Interface2 -> Class2
Interface -> Base -> Class2

The interface is not 'merged' in the derivation tree, interface2 does not inherit virtually from interface, so it'll have its own interface super class. It's like the pure virtual method() exists twice in Class2, once implemented via Class, and once not-implemented.

And even if you had inherited virtually, the common base (Interface) still would not have an implementation

If Base contains trivial operations that should be usuable in the whole hierarchy, then why not have Base as your startpoint? (even if still pure virtual with an implementation).

If this was just a very simple example to make the question short, something like the Bridge Pattern might be more usefull. But it's hard to guide you further without knowing more.

3
  • Thank you for your analysis. It describes why my approach is probably not viable in C++. I like the word "merged", it exactly describes what I want. I hoped that virtual multiple inheritance will do this for me. In the end I will probably end with an non-abstract hierarchy with Base as the root like you suggest, loosing all the advantages of purely abstract interfaces.
    – danatel
    Apr 30, 2009 at 13:21
  • 1
    Good points, and perhaps Base could be made the root class in this instance, but there are cases when that would be a bad idea -- e.g. if Base introduced member variables. In that case, making Base the root would forever tie derived classes to carrying these members around, even if they were never used. Remember, Base just contains stuff that is often convenient -- but it's not necessary for implementing a Interface. Apr 30, 2009 at 13:23
  • 1
    NOTE: markh44's excellent answer shows that by using virtual inheritance, methods can in fact be merged in C++. May 1, 2009 at 2:55
3

You should also look at defining a virtual destructor in your Interface if you might be deleting using an Interface or Base pointer.

Without a virtual destructor you will have problems if you do something like:

Base *b = new Class2();
delete b;
3
  • 1
    ++1 This will cause you all kinds of headaches. Apr 30, 2009 at 13:29
  • Thank you for your comment. Existence of virtual destructors is known to me, I just wanted to make the example short.
    – danatel
    Apr 30, 2009 at 13:33
  • That's good to hear. Just making sure as it can trip people up if they're not aware of it.
    – Steven
    Apr 30, 2009 at 14:49
3

Regarding Class: All you need to do is derive Class from Base -- the fact that it implements Interface is implied, and in fact, inescapable:

class Class: public Base  // virtual inheritance is unnecessary here
{
};

Class will inherit method() from Base as desired.

Regarding Class2:

Disclaimer: Negative result ahead

Based on your comment on Tom's answer, I thought I had the answer for Class2:

// concrete class - specialised
class Class2: public Interface2, public Base
{
public:
    using Base::method;    // "Imports" all members named "method" from Base
};

But actually, this doesn't work. Grovelling through the C++ standard reveals that section 7.3.3, paragraph 14 explains that using can't be used to resolve ambiguous accesses to inherited members:

... [Note: because a using-declaration designates a base class member (and not a member subobject or a member function of a base class subobject), a using-declaration cannot be used to resolve inherited member ambiguities. ...]

It seems that the only way to get the desired behaviour in Class2 is to manually forward the method:

// concrete class - specialised
class Class2: public Interface2, public Base
{
public:
     virtual int method() { return Base::method(); }
};

Regarding virtual inheritance: You don't need it for Class's declaration, but you probably do need it for Interface2's declaration to ensure that Class2 only has a single subobject of type Interface -- as it stands, every Class2 object has two subobjects of this type. (Although that won't cause problems if Interface is in fact a pure interface, lacking member variables.) If it helps, draw a diagram: every time a base class appears without the keyword virtual, it appears as a distinct object; all base classes that appear with the keyword virtual are condensed into one object.

[UPDATE: markh44's excellent answer shows that the above approach (of making Interface2 inherit virtually from Interface) will in fact allow Class2 to automatically inherit the implementation of method() from Base! Problem solved!]

2
  • 1
    Thank you. Class always got compiled. I added Class just to show, that in C++ abstract interface works when the interface is used directly. When there is an hierarchy of interfaces, base methods are not merged from the second level of hierarchy.
    – danatel
    Apr 30, 2009 at 13:28
  • You're welcome. Your comment's a good summary of the issues BTW. Apr 30, 2009 at 13:33
2

This answer in a different forum seems to tackle the exact problem you mention.

1
  • In my case, A and B have the same common base. C inherits directly from B and indirectly from D which inherits from A having the same abstract interface as A.
    – danatel
    Apr 30, 2009 at 18:40
1

In general, you should avoid the diamond inhertance pattern:

            Interface
            /      \
          Base   Interface2
            \      /
             Class2

This will cause you call kinds of grief down the road if you're not careful. Ambiguity will bite you.

In your specific instance there's no need for Interface2 to inherit from Interface. Interface2 doesn't need to specify "method" since it's abstract. Remove the inheritance between Interface and Interface2 to break the diamond. Then you're hierarchy looks like:

        Interface                Interface  Interface2
           |                          |       |
          Base                      Base      |
           |                           \      /
         Class                          Class2

And your implementation looks like:

// concrete class - not specialised - OK
class Class: public Base
{
};

// concrete class - specialised
class Class2: public Base, public Interface2
{
    virtual int method() {return 35;}

    virtual void Inteface2Method { ... }
};
1
  • 1
    OK, I agree it's generally a good idea to avoid the DDD, but what if Interface2 is really a superset (superinterface) of Interface? Are you really saying that there is no way of representing this relationship in C++? Apr 30, 2009 at 13:26

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.