Delete virtual function from a derived class

后端 未结 5 1989
萌比男神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条回答
  •  时光说笑
    2021-01-30 09:55

    "I have a virtual base class function which should never be used in a particular derived class."

    In some respects that is a contradiction. The whole point of virtual functions is to provide different implementations of the contract provided by the base class. What you are trying to do is break the contract. The C++ language is designed to prevent you from doing that. This is why it forces you to implement pure virtual functions when you instantiate an object. And that is why it won't let you delete part of the contract.

    What is happening is a good thing. It is probably preventing you from implementing an inappropriate design choice.

    However:

    Sometimes it can be appropriate to have a blank implementation that does nothing:

    void MyClass::my_virtual_function()
    {
        // nothing here
    }
    

    Or a blank implementation that returns a "failed" status:

    bool MyClass::my_virtual_function()
    {
        return false;
    }
    

    It all depends what you are trying to do. Perhaps if you could give more information as to what you are trying to achieve someone can point you in the right direction.

    EDIT

    If you think about it, to avoid calling the function for a specific derived type, the caller would need to know what type it is calling. The whole point of calling a base class reference/pointer is that you don't know which derived type will receive the call.

提交回复
热议问题