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”.
Example:
CPP
// C++ Program to Illustrate How// Default Virtual Behave// Different in C++ and Java// Importing required libraries// Input output stream#include <iostream>using namespace std;// Class 1// Superclassclass Base { // Granting public access via // public access modifierpublic: // In c++, non-virtual by default // Method of superclass void show() { // Print statement cout << "Base::show() called"; }};// Class 2// Subclassclass Derived : public Base { // Granting public access via public access modifierpublic: // Method of subclass void show() { // Print statement cout << "Derived::show() called"; }};// Main driver methodint main(){ // Creating object of subclass Derived d; // Creating object of subclass // with different reference Base& b = d; // Calling show() method over // Superclass object b.show(); getchar(); return 0;} |
Output:
Base::show() called
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.
Example:
Java
// Java Program to Illustrate// How Default Virtual Behave// Different in C++ and Java// Importing required classesimport java.util.*;// Class 1// Helper classclass Base { // Method of sub class // In java, virtual by default public void show() { // Print statement System.out.println("Base::show() called"); }}// Class 2// Helper class extending Class 1class Derived extends Base { // Method public void show() { // Print statement System.out.println("Derived::show() called"); }}// Class 3// Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Creating object of superclass with // reference to subclass object Base b = new Derived(); ; // Calling show() method over Superclass object b.show(); }} |
Derived::show() called
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.


