Possible Duplicate:
How do you declare an interface in C++?
Interface as in java in c++?
I am a Java programmer learning C++, and I was wondering if there is something like Java interfaces in C++, i.e. classes that another class can implement/extend more than one of. Thanks. p.s. New here so tell me if I did anything wrong.
In C++ a class containing only pure virtual methods denotes an interface.
Example:
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 aninterface
can be declared in a base class.[EXAMPLE:
D
inherits too function declarations:B1::foo()
andB2::foo()
.B2::foo()
is pure virtual, soD::B2::foo()
is too;B1::foo()
doesn't overrideB2::foo()
becauseB2
isn't a derived class ofB1
.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.