Default Virtual Behavior in C++ vs Java



The default behaviour of virtual functions in C++ and Java is significantly different, especially in terms of the handling of method overriding and polymorphism.

Default Virtual Behavior in C++

C++ methods are non-virtual by default. To enable dynamic polymorphism, the virtual keyword must be explicitly used in the base class when defining a method. If virtual is not given, the method call is handled at compile time using the object of static type.

Example

In this example, we implement the default behaviour of the virtual function in C++:

Open Compiler
#include <iostream> using namespace std; class Base { public: void nonVirtualMethod() { cout << "non virtual method" << endl; } virtual void virtualMethod() { cout << "virtual method" << endl; } }; class Derived: public Base { public: void nonVirtualMethod() { cout << "Derived non virtual method" << endl; } void virtualMethod() override { cout << "Derived virtual method" << endl; } }; int main() { Base * basePtr = new Derived(); basePtr -> nonVirtualMethod(); basePtr -> virtualMethod(); // Clean up dynamically allocated memory delete basePtr; return 0; }

Following is the output of the above code:

non virtual method
Derived virtual method

Default Virtual Behavior in Java

However, in Java, all non-static and private methods are virtual by default. It shows that method calls are resolved at runtime using the object of actual type. We can use the final keyword to prevent the method from being overridden, simply making it non-virtual.

Example

In this example, we implement the default behaviour of the virtual function in Java:

Open Compiler
class Base { public void nonFinalMethod() { System.out.println("Base::Default Virtual Method"); } public final void finalMethod() { System.out.println("Base::Non-Virtual Method"); } } class Derived extends Base { @Override public void nonFinalMethod() { System.out.println("Derived::nonFinalMethod"); super.nonFinalMethod(); } //void finalMethod() {} // Compile-time error: cannot override final method } public class Main { public static void main(String[] args) { Base baseObj = new Derived(); baseObj.nonFinalMethod(); baseObj.finalMethod(); } }

Following is the output:

Derived::nonFinalMethod
Base::Default Virtual Method
Base::Non-Virtual Method

Let's discuss the above difference in the table below:

Features C++ Java
Default Behaviour Non-Virtual Virtual
Polymorphism Required explicit "virtual" keyword Enabled by default for non-static, non-private method
Method Overriding Only occurs if the base method declared as virtual Occurs by default unless the method is final
Early/Late Binding Early binding for non-virtual, late binding for virtual Late binding for all non-final, non-static, non-private methods
Updated on: 2025-05-16T17:05:01+05:30

166 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements