I'm having some confusion regarding the virtual mechanism in C ++ and Java. The output of the following programs is different. I canβt understand why?
In Java:
class Base { Base() { show(); } public void show() { System.out.println("Base::show() called"); } } class Derived extends Base { Derived() { show(); } public void show() { System.out.println("Derived::show() called"); } } public class Main { public static void main(String[] args) { Base b = new Derived(); } }
Exit:
Derived::show() called Derived::show() called
While in C ++ the following is output:
#include<bits/stdc++.h> using namespace std; class Base { public: Base() { show(); } virtual void show() { cout<<"Base::show() called"<<endl; } }; class Derived : public Base { public: Derived() { show(); } void show() { cout<<"Derived::show() called"<<endl; } }; int main() { Base *b = new Derived; }
is an:
Base::show() called Derived::show() called
Can someone explain?
source share