NmdMystery
NmdMystery

Reputation: 2868

C++ Prevent multiple inheritance of two classes by the derived classes of a certain class

Kind of a verbose title, but here goes:

I have a situation where I want to prevent two classes from being derived by the same class or any class of a family. In code:

    class A;
    class B;

    class C: public A; //Yes.
    class D: public B; //Yes.

    class E: public A, public B; //Yes.
    class F: public C, public B; //Yes.

    class G: public A /*Disallow inheritance of B at this point somehow*/;
    class H: public G, public B; //Error at this point...

    class I;
    class J: public G, public I; //...but not at this point.

It's a situation where the private members of A and B are to remain private from any derived classes, and friendship would ruin that design. How would I be able to do this?

Upvotes: 1

Views: 484

Answers (1)

πάντα ῥεῖ
πάντα ῥεῖ

Reputation: 1

Without really looking deeper, it looks like a typical problem that's used to be solved using static (compile time resolved) polymorphism. The basic approach for such frameworks is the CRTP meta programming pattern (simply because you introduce a strong policy for your inheriting class in how your parent/base classes can be used or combined).

Have a look at how to provide

  • type traits (there are some libs available to support this before C++11 stdandard compliance)
  • concept checks (several libs support this, e.g. boost::concept_check)
  • SFINAE and/or explicit (compile time) error conditions

You might consider various discrete client helper (API) classes to aggregate interface implementations for your final classes; this refers to hiding certain implementations in compilation units and eventually necessary factories for creation of concrete instances.

Upvotes: 2

Related Questions