2

I have a project with some very small classes that act as minimal interfaces for larger classes. Sometimes I have objects that need several of these interfaces. And sometimes these interfaces share the same derived base class. Is there anyway that I can structure my code so that I only have one copy of that derived base class that all of the interfaces share?

Here's a code example:

class A {
public:
  virtual void f(int a)=0;
  virtual int g() const {
    return m_inner;
  }
protected:
  int m_inner;
};

class B : public A {
public:
  virtual void f(int a)=0;
  virtual void h(int b) {
    m_stuff = b;
    m_inner = 0;
  }
protected:
  int m_stuff;
};

class C : public A {
public:
  virtual void f(int a)=0;
  virtual int i() const {
    return m_otherstuff;
  }
protected:
  int m_otherstuff;
};

class D : public B, public C {
public:
  void f(int a) { //do stuff }
  //fill in the rest of a big actual class.
}; 

D has two copies of A and referencing A:: is ambiguous. What's the best way to structure my classes so that I get only one copy of A at the end of the day? I'm willing to restructure A, B and C in whatever fashion. Is this even possible?

OmnipotentEntity
  • 16,531
  • 6
  • 62
  • 96

3 Answers3

5

Virtual inheritance is what you need. Your case is a typical diamond problem. Have a brief search on google or any c++ book should give u plenty of related info

Adrian Shum
  • 38,812
  • 10
  • 83
  • 131
3

I'm not much into C++ but I know this is called Diamond Problem.

and, this is your solution.

Azodious
  • 13,752
  • 1
  • 36
  • 71
1

Virtual inheritance will solve your immediate problem (already answered here). But, I strongly suggest you to re-think the hierarchy. I have never seen virtual inheritance used except in academic papers and in some cases of extreme refactoring. Perhaps, you may get away by using aggregation instead of inheritance.

Community
  • 1
  • 1
blinnov.com
  • 305
  • 1
  • 5