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
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
.