To emulate Java interface
, you can use an ordinary base with only pure virtual functions.
You need to use virtual inheritance, otherwise you could get repeated inheritance: the same class can be a base class more than once in C++. This means that access of this base class would be ambiguous in this case.
C++ does not provide the exact equivalent of Java interface
: in C++, overriding a virtual function can only be done in a derived class of the class with the virtual function declaration, whereas in Java, the overrider for a method in an interface
can be declared in a base class.
[EXAMPLE:
struct B1 {
void foo ();
};
struct B2 {
virtual void foo () = 0;
};
struct D : B1, B2 {
// no declaration of foo() here
};
D
inherits too function declarations: B1::foo()
and B2::foo()
.
B2::foo()
is pure virtual, so D::B2::foo()
is too; B1::foo()
doesn't override B2::foo()
because B2
isn't a derived class of B1
.
Thus, D
is an abstract class.
--end example]
Anyway, why would you emulate the arbitrary limits of Java in C++?
EDIT: added example for clarification.