Last Updated : 23 Jul, 2025
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
// Superclass
class Base {
// Granting public access via
// public access modifier
public:
// In c++, non-virtual by default
// Method of superclass
void show()
{
// Print statement
cout << "Base::show() called";
}
};
// Class 2
// Subclass
class Derived : public Base {
// Granting public access via public access modifier
public:
// Method of subclass
void show()
{
// Print statement
cout << "Derived::show() called";
}
};
// Main driver method
int 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 classes
import java.util.*;
// Class 1
// Helper class
class 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 1
class Derived extends Base {
// Method
public void show()
{
// Print statement
System.out.println("Derived::show() called");
}
}
// Class 3
// Main class
public 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.
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4