Open In App

How Does Default Virtual Behavior Differ in C++ and Java?

Last Updated : 15 Jan, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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();
    }
}


Output

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.

 



Previous Article
Next Article

Similar Reads

How does 'void*' differ in C and C++?
C allows a void* pointer to be assigned to any pointer type without a cast, whereas in C++, it does not. We have to explicitly typecast the void* pointer in C++ For example, the following is valid in C but not C++: void* ptr; int *i = ptr; // Implicit conversion from void* to int* Similarly, int *j = malloc(sizeof(int) * 5); // Implicit conversion
1 min read
Behavior of virtual function in the derived class from the base class and abstract class
In this article, we will discuss the behavior of Virtual Function in the derived class and derived class from the Abstract Base Class in C++. Consider the following program: C/C++ Code // C++ program to illustrate the concept // of Virtual Function #include &lt;bits/stdc++.h&gt; using namespace std; // Base Class class Base { public: // Virtual Fun
3 min read
Java Program to Illustrate the Availability of Default Constructor of the Super Class to the Sub Class by Default
A constructor in Java is a special method that is used to initialize an object. Whenever an object is created using the new() keyword at least one construction is called. The constructor name must match with the class name and cannot have a return type. If there is no constructor available in the class in such a case java compiler provides a defaul
5 min read
Default Arguments and Virtual Function in C++
Default Arguments are the values provided during function declaration, such that values can be automatically assigned if no argument is passed to them. In case any value is passed the default value is overridden and it becomes a parameterized argument. Virtual function is a member function that is declared within a base class and is redefined(Overr
3 min read
When Does Compiler Create Default and Copy Constructors in C++?
A constructor is a special type of member function of a class that initializes objects of a class. In C++, Constructor is automatically called when an object(instance of a class) is created. There are 3 types of constructors in C++ Default ConstructorCopy constructorParameterized ConstructorIn C++, the compiler creates a default constructor if we d
3 min read
Difference between Virtual function and Pure virtual function in C++
Virtual Function in C++ A virtual function is a member function which is declared within a base class and is re-defined(Overridden) by a derived class. When you refer to a derived class object using a pointer or a reference to the base class, you can call a virtual function for that object and execute the derived class’s version of the function. Pu
2 min read
Does C++ compiler create default constructor when we write our own?
No, the C++ compiler doesn't create a default constructor when we initialize our own, the compiler by default creates a default constructor for every class; But, if we define our own constructor, the compiler doesn't create the default constructor. This is so because the default constructor does not take any argument and if two default constructors
1 min read
What happens when a virtual function is called inside a non-virtual function in C++
Predict the output of the following simple C++ program without any virtual function. C/C++ Code #include &amp;lt;iostream&amp;gt; using namespace std; class Base { public: void print() { cout &amp;lt;&amp;lt; &amp;quot;Base class print function \n&amp;quot;; } void invoke() { cout &amp;lt;&amp;lt; &amp;quot;Base class invoke function \n&amp;quot;;
2 min read
Abnormal behavior of floating point and double values
Float is a 32 bit IEEE 754 single-precision Floating Point Number 1 bit for the sign, (8 bits for the exponent, and 23* for the value), i.e. float has 7 decimal digits of precision. Double is a 64 bit IEEE 754 double precision Floating Point Number (1 bit for the sign, 11 bits for the exponent, and 52* bits for the value), i.e. double has 15 decima
6 min read
Undefined Behavior in C and C++
When we run a code, sometimes we see absurd results instead of expected output. So, in C/C++ programming, undefined behavior means when the program fails to compile, or it may execute incorrectly, either crashes or generates incorrect results, or when it may fortuitously do exactly what the programmer intended. Whenever the result of an executing p
7 min read
Article Tags :
Practice Tags :