3 ms·
"why is the keyword 'virtual' even necessary? Surely all methods should be virtual by default (and the compiler ought to be able to replace virtual calls with d
by timr 18y ago
"why is the keyword 'virtual' even necessary? Surely all methods should be virtual by default (and the compiler ought to be able to replace virtual calls with direct calls based on the type information)."
And how is the compiler supposed to determine the (possibly dynamic) type of an object at compile time, in order to determine when to make the call statically?
If you declare a method virtual, you're telling the compiler to use late binding. If you don't, you're telling the compiler to use early binding. You always know what you're going to get. That's why the keyword is there -- so you don't have to guess.
"Can anyone cite an example of where you'd actually want to call different methods depending on whether you're using a base or a derived pointer?"
Not sure what you're asking here. Are you talking about the ability to hide a base class method with a derived class method? It's not really considered a good idea to do such a thing (see: http://www.parashift.com/c++-faq-lite/strange-inheritance.html#faq-23.8 http://www.parashift.com/c++-faq-lite/strange-inheritance.ht...), but it's an inevitable consequence of mixing early- and late-binding features in the same language.
- qwph 18y agoAre you talking about the ability to hide a base class method with a derived class method? It's not really considered a good idea to do such a thing, but it's an inevitable consequence of mixing early- and late-binding in the same language Yes. It sounds like we agree that overriding a non-virtual method is a bad idea, and i think "mixing early- and late-binding" probably captures it quite well. The C++ compiler makes the programmer decide whether to use early or late binding, and handle the consequences. In some other languages (let's say Self, for example), the distinction between early and late binding is handled by the compiler, so it's invisible at source level, and all methods are (implicitly) virtual unless the compiler can prove that a static call is safe, in which case it can inline the call. That means that the "early-binding conflict" situation can't arise in a language like Self.