Delete virtual function from a derived class

后端 未结 5 1999
萌比男神i
萌比男神i 2021-01-30 09:06

I have a virtual base class function which should never be used in a particular derived class. Is there a way to \'delete\' it? I can of course just give it an empty definitio

5条回答
  •  闹比i
    闹比i (楼主)
    2021-01-30 09:52

    The standard does not allow you to delete any member of a base-class in a derived class for good reason:
    Doing so breaks inheritance, specifically the "is-a" relationship.

    For related reasons, it does not allow a derived class to define a function deleted in the base-class:
    The hook is not any longer part of the base-class contract, and thus it stops you from relying on previous guarantees which no longer hold.

    If you want to get tricky, you can force an error, but it will have to be link-time instead of compile-time:
    Declare the member function but don't ever define it (This is not 100% guaranteed to work for virtual functions though).
    Better also take a look at the GCC deprecated attribute for earlier warnings __attribute__ ((deprecated)).
    For details and similar MS magic: C++ mark as deprecated

提交回复
热议问题