Reputation: 13598
This question explains nicely how to create interfaces in C++. Here is the code:
class IDemo
{
public:
virtual ~IDemo() {}
virtual void OverrideMe() = 0;
};
class Parent
{
public:
virtual ~Parent();
};
class Child : public Parent, public IDemo
{
public:
virtual void OverrideMe()
{
//do stuff
}
};
One thing is not clear to me though: What do I need the class Parent
for?
Upvotes: 0
Views: 130
Reputation: 25919
Actually, I have no idea, why. You can do the following as well:
class IDemo
{
public:
virtual ~IDemo() {}
virtual void OverrideMe() = 0;
};
class Child : public IDemo
{
public:
virtual void OverrideMe()
{
//do stuff
}
~Child()
{
}
};
Everything depends only on your program's architecture and what actually Parent
and Child
are. Look at the C# example - IDisposable
is an interface, which allows one to dispose resources used by the class, which implements it. There is no point in requiring a base class - it would even make using IDisposable
harder to use, because maybe I don't want the base class functionalities (despite fact, that every .NET class derives from Object
, but that's another story).
If you provide more information about your actual program's architecture, we may be able to judge, whether a base class is needed or not.
There's another thing worth pointing out. Remember, that in C++ IDemo actually is a class, it's an interface only from your point of view. So in my example, Child actually has a base class.
Upvotes: 1
Reputation: 170529
You're not required to inherit from anything besides your interface to make use of the interface, however you can do so and that answer shows you how. The point is you're not required to only inherit from one or several interfaces, you can also add classes as bases of your class - almost any combination of classes and interfaces is permitted.
Upvotes: 4