Default virtual behavior in C++ vs Java


In C++ methods are non-virtual by default. They can be made virtual function by using a virtual keyword.

Example Code

#include <iostream>
using namespace std;
class B {
   public: void s() //non virtual by default. Use virtual before the function to print “In Derived” {
      cout<<" In Base \n";
   }
};

class D: public B {
   public: void s() {
      cout<<"In Derived \n";
   }
};

int main(void) {
   D d; // An object of class D
   B &b = d;
   b.s();
   return 0;
}

Output

In Base.

In Java, methods are virtual by default. They can be made non-virtual function by using the final keyword.

Example Code

class B {
   public void s() {
      System.out.println("In Base"); // virtual by default
   }
}

class D extends B {
   public void s() {
      System.out.println(" In Derived");
   }
}

public class Main {
   public static void main(String[] args) {
      B b = new D();
      b.show();
   }
}

Output

In Base.
raja
Published on 03-Apr-2019 16:09:45
Advertisements