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
#include <iostream>
using namespace std;
class Base {
public :
void show()
{
cout << "Base::show() called" ;
}
};
class Derived : public Base {
public :
void show()
{
cout << "Derived::show() called" ;
}
};
int main()
{
Derived d;
Base& b = d;
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
import java.util.*;
class Base {
public void show()
{
System.out.println( "Base::show() called" );
}
}
class Derived extends Base {
public void show()
{
System.out.println( "Derived::show() called" );
}
}
public class GFG {
public static void main(String[] args)
{
Base b = new Derived();
;
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.
Last Updated :
15 Jan, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...