I am having some confusion related to virtual mechanism in C++ and Java. The output of the following programs are different. I am not able to 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();
}
}
The Output is:
Derived::show() called
Derived::show() called
While in C++, the output of the following:
#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:
Base::show() called
Derived::show() called
Can anybody please explain?