How to avoid conflict in inheritance

In my C++ program, I have two classes (B1 and B2) with their own methods but 1 ("accidentally") in common. For example:

class B1 header:

void height();
void size();
void enabled();

class B2 header:

void width();
void length();
void enabled();

Now I have a class A that inherit from B1 and B2. Since I have a "conflict" in method enabled() after multiple inheritance, how can I avoid this? Is there a way to exclude a method from inheritance? For example I could exclude enabled() inheritance from class B1 (I cannot set it private since it's used from other classes derived from B1). Any other idea?

Answers


You can solve the ambiguity but you will inherit both functions anyway. There is no way you can choose not to inherit some function. To fix the ambiguity use the following:

class B1
{
public:
    void height();
    void size();
    void enabled();
};

class B2
{
public:
    void width();
    void length();
    void enabled();
};

class A: public B1, public B2
{
public: 
    using B2::enabled;
};

You can try using namespaces. Make B1::enabled() a member of namespace called X and B2::enabled() - Y. In the derived class use X::enabled() or Y::enabled().


You can disambiguate your calls to base class methods using the syntax Class::function. In your case, wherever you use enabled, qualify the call:

B1::enabled();
B2::enabled();

If you only need one of those functions, you can write a using-declaration:

using B1::enabled;

Personally I would encapsulate B in an A and provide an interface to anything useful it provides in A that you need outside of it, rather than inheriting. If you need polymorphic behaviour, make both A and B inherit from the same abstract interface.


Need Your Help

Adding a New Line in iTextSharp

c# itextsharp newline

I’ve been trying to solve this problem for a while now to no avail. I have some text in iTextSharp I’m trying to put on a newline. I’ve tried using the \n escape character, Environment.NewLine, and