I want to know if there is a way to specify that in multiple inheritence, one of the base-classes virtual functions becomes the single virtual definition. They only way I see to do this is by writing an explicit definition of this function in the derived class and explicitly call one of the base classes. This is cumbersome, and I was hoping using might help, but it doesn’t.
For example, in the below code, I have to define a C::value even though I just wish to forward to the class B version. Is there not a simpler way?
#include <iostream>
using namespace std;
struct A
{
virtual char const * value() const
{ return "A"; }
};
struct B
{
virtual char const * value() const
{ return "B"; }
};
class C : public A, public B
{
public:
//using B::value;
virtual char const * value() const
{ return B::value(); }
};
int main()
{
C obj;
cout << obj.value() << endl;
A * ptr = &obj;
cout << ptr->value() << endl;
}
Some notes:
- in this particular case virtual inheritance of class A is not an option for Class B — I need a proper construction chain down to the base
- In theory struct B could also be used unrelated to A, but that is not the case here (in case that provides other options)
valuemay be marked as pure virtual if that somehow helps, but I don’t believe it does.- there are other classes which derive from A but not B
- to be clear, however “func” is called on C, through any type pointer, must result in “B”
I suspect the answer might be “No”, but some confirmation would be good. It feels like the language should support this pattern.
usingkeyword in your context is used only to bring the names into the current scope (used against name hiding). Assume that your requested feature is already there. Now see the below modified codes:Suppose we have functions of the same name as
value(int)inCandvalue(double)inA. These 2 functions have nothing to do withvirtual value()and are used with object ofC.How will you use
A::value(double)withC‘s object ? Naturally you have to dousing A::value;in body ofC. Now because of this, as a side effect we have 2virtualfunction match:A::value() constandB::value() const!Which to choose when called with
A*orB*?This is only one example, but there can be other problems too. Whatever you have mentioned in your question is the best way to accomplish the correct result. It explicitly says that
C::value() constis a wrapper aroundB::value() const.