Why does C++ make you specify which functions are virtual?

Hi, I've been learning Java and C++, and was wondering what the advantage is to the way C++ handles virtual functions, where you have to explicitly state which functions are virtual, and the way Java does this, where every function can be polymorphic unless otherwise specified. It seems like Java's way of doing it is better, but is there some benefit to how C++ does it? All that I can think of is that C++'s way makes it easier to use the base-class definition of a function, but the number of times you would want to do this compared to how often you want to treat them polymophically again makes it seem like Java's way is better.
Because making a function virtual forces a run-time speed cost that you might not want in C++. Java doesn't care so much about speed so they decided to make them all virtual for you by default.
Adding a virtual function to a class (if the class previously had no virtual functions) adds space overhead to each instance of the class to hold the virtual table, plus time overhead at each call to the function.
Requiring the programmer to explicitly state that a function is virtual is part of C++'s zero overhead principle. If your classes don't use polymorphism, you don't need to pay for it.
Ah, that makes a lot of sense. Thank you both for the quick responses.
Last edited on
in essence, all Java methods are virtual

in C++, you only pay for what you ask for - however, once a method is declared virtual in the base, it's virtual in the child classes, even if you don't use the keyword

that having said, many optimizing compilers will attempt to determine, at compile time, if the type for a variable is fixed - if it is, the extra indirection due to a virtual method will be optimized away
Topic archived. No new replies allowed.