Perhaps i have two interfaces with same function names and parameters, but with different return values:
struct A { virtual void foo() = 0; };
struct B { virtual int foo() = 0; };
How to define class C, that inherits this interfaces (if it's of course possible)? For example i write some pseudocode that doesn't compiled:
// this code is fake, it doesn't compiled!!
struct C : A, B
{
// how to tell compiler what method using if referenced from C?
using void foo(); // incorrect in VS 2012
// and override A::foo() and B::foo()?
virtual void foo() { std::cout << "void C::foo();\n"; } // incorrect
virtual int foo() { std::cout << "int C::foo();\n"; return 0; } // incorrect
}
// ... for use in code
C c;
A &a = c;
B &b = c;
c.foo(); // call void C::foo() when reference from C instance
a.foo(); // call void C::foo() when reference from A instance
b.foo(); // call int C::foo() when reference from B instance
As we have explained in the inheritance chapter, multiple inheritance is not supported in the case of class because of ambiguity. However, it is supported in case of an interface because there is no ambiguity.
An interface contains variables and methods like a class but the methods in an interface are abstract by default unlike a class. Multiple inheritance by interface occurs if a class implements multiple interfaces or also if an interface itself extends multiple interfaces.
Master C and Embedded C Programming- Learn as you go So the class can inherit features from multiple base classes using multiple inheritance. This is an important feature of object oriented programming languages such as C++.
If two interfaces contain a method with the same signature but different return types, then it is impossible to implement both the interface simultaneously.
It's not possible, but not because of the multiple inheritance. Ambiguity arises due to invalid overload of foo
in class C
. You can't have both int foo()
and void foo()
since return type is not part of function signature, thus the compiler won't be able to resolve the calls to foo
. You can look at your interface as a union of both A
and B
classes, so logically the problem is already present before the actual inheritance. Since from compiler perspective A
and B
are 2 distinct and unrelated types, there is no problem while compiling them and the error is delayed until point of actual unification in class C
.
See more here about function signatures and overloading: Is the return type part of the function signature?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With