Bryn McKerracher
Bryn McKerracher

Reputation: 683

C++ Context-Based Class Implementation

Is it possible in C++ to have a class whose definition depends on the context of its construction?

For example, could a class A with multiple constructors inherit from class B following a call to a particular constructor, while instead inheriting from class C following a call to a different constructor?

If not, why? And if so, how would this be accomplished?

Upvotes: 2

Views: 1637

Answers (2)

Christophe
Christophe

Reputation: 73510

No, this is not possible dynamically.

If A inherits from B , it should be some kind of B ("is-a" relationship). This relationship stands for all the objects of class A, independently of the context.

The fact that you want to inherit sometimes from B, sometimes from C suggests that you are thinking of a "has-a" relationship. This would be implemented by composition:

class B; 
class C; 
class A {
    B *hasB;   // of course in real lif you'd use unique_ptr or shared_ptr...
    C *hasC; 
public:  
    A(B *b);  // would set hasB but set hasC to nullptr. 
    A(C *c);  // would set hasC but set hasB to nullptr. 
    ...
};

If your problem has not to be handled dynamically, but only at compilation time, you could think of templates:

template <class T>
class A : public T {
    ...
};    

A<B> ab;  // A<B> inherits from B 
A<C> ac;  // A<C> inherits from C
// but attention:  both class are two different classes.  

Upvotes: 2

iheanyi
iheanyi

Reputation: 3113

Yes. But not in the manner you've explicitly proposed. Inheritance is independent of constructor - so you couldn't achieve this "context specific" behavior in that manner.

Here's a couple options (note, there are more ways to do this):

A relatively straightforward way, especially if you want to hide that your class A has features of classes B or C, is to privately inherit from B and C. Then set a flag in the constructor that tells the class to use features from B or features from C. Then all your class A methods just check that parameter and call the appropriate B or C methods.

Alternatively, you can use templates. The Visitor pattern comes to mind as one template-based approach that accomplishes what you seem to describe.

Upvotes: 1

Related Questions