Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
333 views
in Technique[技术] by (71.8m points)

c++ - virtual desctructor on pure abstract base class

I have

struct IMyInterface
{
   virtual method1() = 0;
   virtual method2() = 0;
};

GCC insists that I have

struct IMyInterface
{
   virtual method1() = 0;
   virtual method2() = 0;
   virtual ~IMyInterface(){};
};

I dont see why. A pure interface is all about the interface (duh). The destructor is part of the internal implementation details of a concrete implementer of the interface; it does not form part of the interface. I understand the whole slicing issue (or at least I think I do)

So my question is - is GCC right to insist on it and if so why?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

According to the C++ spec, yes.

You need to declare the destructor virtual because otherwise, later

    IMyInterface * ptr = getARealOne();
    delete ptr;

won't call the destructor on the derived class (because the destructor isn't in the VTable)

It needs to be non-pure because base class destructors are always called by the sub-class destructor.

To further explain, C++ doesn't have a concept of an interface in the same way that Java or C# do. It's just a convention to use only pure-virtual methods, and think of that as an interface. The other rules about C++ destructors make it need to be non-pure, which breaks the similarity to interfaces in other languages, but those languages didn't exist at the time these rules were made.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...