Class member functions are initially non-virtual as the default behavior in C++. By explicitly declaring them as such, they can be transformed into virtual functions.
In Java, methods are inherently virtual and can be explicitly defined as non-virtual by utilizing the 'final' keyword.
In C++, it's essential to note that class member methods are non-virtual by default, unlike Java where they are virtual by default. The virtual keyword is used in C++ to make methods virtual. For instance, in the given program, Base :: show is not declared as virtual, resulting in the output "Base::show called."
// 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
Compilation Error
Base :: show() called
Adding the term "virtual" before defining Base::show results in the program outputting "Derived::show called." In Java, methods are inherently virtual, unless declared as non-virtual using the final keyword. In the provided Java program, the show method is virtual by default, leading to the output "Derived::show called."
Let's observe the outcome when applying the identical concept within the Java programming language, as demonstrated in the following example.
// 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();
}
}
Output
Derived :: show() called