I am wonder it is available to Declare interface and Implement the interface using multi-inheritance.
For example.
I Declare abstract class for interface.
class Interface{
public:
virtual int interf1(int a) = 0;
virtual int interf2(char c) = 0;
};
And than to implement these two interface, i define two classes for each, like below
class Implement1{
public:
int interf1(int a){
std::cout << a << a << std::endl;
return 0;
}
};
class Inplement2{
public:
int interf2(char c){
std::cout << c << c << c << std::endl;
return 0;
}
};
And then as Last phase, i define a class which inherit Interface and implement classes all.
class Test : public Interface, public Implement1, public Inplement2{
};
But of course, it is not compiled.
Is there any way to build this kind of functionality?
And Actually i found some way while struggling to make it compiled like below, but i am not sure it is safe way which doesn't make potential error, even though now it seem to work since it is simple code.
class Test : public Interface, private Implement1, private Inplement2{
public:
virtual int interf1(int a){
return Implement1::interf1(a);
};
virtual int interf2(char c){
return Inplement2::interf2(c);
}
};
I suggest two alternatives.
1. Split the interface
Define two interfaces,
Interface1
withinterf1
method, andInterface2
withinterf2
method. Define two implementationsImplement1
andImplement2
which inherit from their corresponding (single) interface. Combine those by inheriting from bothImplement1
andImplement2
.The problem is that you then can't have a common interface to use as a polymorphic interface type.
2. Use virtual inheritance for the interface
Live demo
Keep your original
Interface
definition. The implementations both should virtually derive from the interface:class Implement1 : virtual public Interface { ... };
. Then, when combining those implementations, don't derive from the interface again but just from your two implementations. Their super-classInterface
is going to be merged to a single one (that's what virtual inheritance is for, basically, it's also called Diamond Inheritance).