Delete virtual function from a derived class

后端 未结 5 2009
萌比男神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:37

    What you can do is simply throwing an exception in the derived implementation. For example, the Java Collections framework does this quite excessively: When an update operation is performed on a collection that is immutable, the corresponding method simply throws an UnsupportedOperationException. You can do the same in C++.

    Of course, this will show a malicious use of the function only at runtime; not at compile time. However, with virtual methods, you are unable to catch such errors at compile time anyway because of polymorphism. E.g.:

    B* b = new D();
    b.f();
    

    Here, you store a D in a B* variable. So, even if there was a way to tell the compiler that you are not allowed to call f on a D, the compiler would be unable to report this error here, because it only sees B.

提交回复
热议问题