0

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?

Community
  • 1
  • 1
mort
  • 12,988
  • 14
  • 52
  • 97
  • 2
    While I'm not sure myself, I guess it's merely there to illustrate the concept of multiple inheritance in this context. Basically it shows how you can have multiple 'interfaces' (or parent classes) come together in one class. – ATaylor Mar 28 '13 at 08:05

2 Answers2

4

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.

sharptooth
  • 167,383
  • 100
  • 513
  • 979
1

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.

Spook
  • 25,318
  • 18
  • 90
  • 167
  • Thanks for your answer. I was only interested in how to do that and don't actually have a context in which I use it atm. – mort Mar 28 '13 at 08:35