C++11 Delete overridden Method

北城余情 提交于 2019-12-05 00:54:58

Paragraph 8.4.3/2 of the C++ Standard indirectly forbids deleting a function which overrides a virtual function:

"A program that refers to a deleted function implicitly or explicitly, other than to declare it, is ill-formed. [ Note: This includes calling the function implicitly or explicitly and forming a pointer or pointer-to-member to the function"

Invoking an overriding virtual function through a pointer to the base class is an attempt to implicitly invoke the function. Therefore, per 8.4.3/2, a design that allows this is illegal. Also notice that no C++11 conforming compiler will let you delete an overriding virtual function.

More explicitly, the same is mandated by Paragraph 10.3/16:

"A function with a deleted definition (8.4) shall not override a function that does not have a deleted definition. Likewise, a function that does not have a deleted definition shall not override a function with a deleted definition."

10.3p16:

A function with a deleted definition (8.4) shall not override a function that does not have a deleted definition. Likewise, a function that does not have a deleted definition shall not override a function with a deleted definition.

The other answers explain why pretty well, but there you have the official Thou Shalt Not.

Consider some function:

void f(LibraryVersion1* p)
{
    p->doSomething1();
}

This will compile before LibraryVersion2 is even written.

So now you implement LibraryVersion2 with the deleted virtual.

f has already been compiled. It doesn't know until runtime which LibraryVersion1 subclass it has been called with.

This is why a deleted virtual isn't legal, it doesn't make any sense.

Best you can do is:

class LibraryVersion2 : public LibraryVersion1
{
public:
    virtual void doSomething1() override
    {
         throw DeletedFunctionException();
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!