nimoz
nimoz

Reputation: 25

How to replace base class with derived base class

I'm developing a API in which the class A is derived as class B.

if a API user want to extend the functionality of both class A and class B at application level, then there will be problem.

suppose application user come up with class AX extending class A, and class BX extending class B. In this instance user does not get the expected behavior for class BX since class Bs' base class is class A NOT class AX.

Thought : Application user may extend the class BX using both class B and class AX, but in this case I think there will be known diamond behavior.

I would like know, any standard way of resolving this issue.

Upvotes: 0

Views: 1007

Answers (4)

Zero
Zero

Reputation: 12099

class InterfaceA;

class InterfaceB;

class A : public InterfaceA;

template<class AType>
class B_Template : public InterfaceB, public AType;

// Below is same as class B in example
// Users can use B as if it was class B
typedef B_Template<A> B;   

// User can extend A
class AX : A;

// User can extend B any way they want (you can't police this)
// but the way you wanted in the question was:
class BX : B_Template<AX>;   // Inherits of the extended AX

This solves your question, but as pointed out in the comments you should consider dependency injection instead of inheritance.

Also, the Interface classes aren't really needed, but it can make it clear what the contract on the base class is - that is the template parameter AType must satisfy InterfaceA.

Upvotes: 0

Ben Voigt
Ben Voigt

Reputation: 283684

A class inheriting from a template parameter is also an option. Pseudo-code:

class A;

template<typename WhichA>
class B : public WhichA;

class AX : public A;

class BX : public B<AX>;

Upvotes: 1

iammilind
iammilind

Reputation: 69988

... but in this case I think there will be known diamond behavior

So what's the problem ? virtual inheritance is meant for resolving such diamond pattern.
If the children of A are virtually inherited, then I don't see any problem, unless the design is changed.

Upvotes: 0

dirkgently
dirkgently

Reputation: 111140

Your question is a bit vague. Anyway, I'd recommend you read the C++ FAQ 25 and Question 25.5 in particular. Questions 25.5 and 25.6 discuss some alternatives.

Upvotes: 1

Related Questions