Possible Duplicate:
How do you declare an interface in C++?
This is a general question about C++. As you know, there is no clear distinction between interface
and abstract class
in C++ unlike Java and C#. When would it be more preferrable to use an interface
instead of an abstract class
in C++? Could you give some examples?
This question is related to
c++
interface
abstract-class
Pure Virtual Functions are mostly used to define:
a) abstract classes
These are base classes where you have to derive from them and then implement the pure virtual functions.
b) interfaces
These are 'empty' classes where all functions are pure virtual and hence you have to derive and then implement all of the functions.
Pure virtual functions are actually functions which have no implementation in base class and have to be implemented in derived class.
Please don't put members into an interface; though it's correct in phrasing. Please don't "delete" an interface.
class IInterface()
{
Public:
Virtual ~IInterface(){};
…
}
Class ClassImpl : public IInterface
{
…
}
Int main()
{
IInterface* pInterface = new ClassImpl();
…
delete pInterface; // Wrong in OO Programming, correct in C++.
}
An abstract class would be used when some common implementation was required. An interface would be if you just want to specify a contract that parts of the program have to conform too. By implementing an interface you are guaranteeing that you will implement certain methods. By extending an abstract class you are inheriting some of it's implementation. Therefore an interface is just an abstract class with no methods implemented (all are pure virtual).
interface
were primarily made popular by Java.
Below are the nature of interface
and its C++ equivalents:
interface
can contain only body-less abstract methods; C++ equivalent is pure virtual
methods, though they can/cannot have bodyinterface
can contain only static final
data members; C++
equivalent is static const
data members which are
compile time constantsinterface
can be implement
ed by a Java class
, this
facility is needed because a Java class
can inherit only 1
class
; C++ supports multiple inheritance straight away with help of virtual
keyword when neededBecause of point 3 interface
concept was never formally introduced in C++. Still one can have a flexibility to do that.
Besides this you can refer Bjarne's FAQ on this topic.
Source: Stackoverflow.com