How Does Default Virtual Behavior Differ in C++ and Java?
Let us discuss how the default virtual behavior of methods is opposite in C++ and Java. It is very important to remember that in the C++ language class member methods are non-virtual by default. They can be made virtual by using virtual keywords. For example, Base::show() is non-virtual in following program and program prints “Base::show() called”.
Output: Compilation error
Output Explanation: Adding virtual before definition of Base::show() makes program print “Derived::show() called”. In Java, methods are virtual by default and can be made non-virtual by using the final keyword. For example, in the following java program, show() is by default virtual and the program prints “Derived::show() called“.
Let us see what happens in the case we use the same concept in a java programming language via the example proposed below.
Note: Unlike C++ non-virtual behavior, if we add final before the definition of the show() in Base, then the above program fails in the compilation.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.