Interfaces in C++: why do I need an interface class + another parent class?

孤街醉人 提交于 2019-12-13 21:22:57

问题


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?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/15676807/interfaces-in-c-why-do-i-need-an-interface-class-another-parent-class

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!