Reputation: 2693
I'm new to programming in c++ and struggle with organizing my project. I have got a class named StateManager, which has a header file and an cpp file. The cpp contains all implementations.
If I now want to make an Interface class:
class IStateManager
{
public:
virtual ~IStateManager() {}
virtual void SomeMethod {}
};
I know interfaces don't really exist as they do in c# or Java, but I want multiple classes to inherit from this "interface".
Does this class also need an header and a cpp file? Or can I just put it in a header file?
Upvotes: 7
Views: 3598
Reputation: 6043
Technically, c++ doesn't have interfaces. However, one can "create" interfaces by way of multiple inheritance (or single inheritance if your class is a "base" class and doesn't need to inherit from multiple classes). Where your "interface" lives is entirely up to you. But if you plan on using a class as an interface (without any actual implementation because technically an interface doesn't have an implementation until the functions are defined in a subclass), I would put it in it's own header file and declare each function pure virtual:
class IStateManager
{
public:
virtual ~IStateManager() {}
virtual void SomeMethod() = 0;
virtual void AnotherMethod() = 0;
};
class TheState : public IStateManager, public SomeOtherParentClass
{
virtual void SomeMethod(); // Defined in this class
virtual void AnotherMethod(); // Also defined in this class
//..
};
If you are defining some implementation in a .cpp for the IStateManager
class, then you really have more of an abstract class and not an interface.
So in conclusion what I'm saying is: Any implementation of an "interface" should be defined in the .cpp file of its implementing class. And if you plan on using the interface in multiple files, I would create a separate .h file for it.
Upvotes: 6
Reputation: 101456
You can put the implementation of class methods in the header file. That doesn't mean you should. It also has nothing to do with the fact that this is an "interface" class, as you call it.
I wouldn't call this an interface class by the way, because your virtual
methods aren't pure.
Upvotes: 1