5

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?

  • 3
    The output is different because you have two completely different programs. Just because the syntax of the programs my look similar, doesn't mean the behavior will be the same. Java and C++ are two completely different languages with completely different behaviors. – Some programmer dude Apr 12 '15 at 16:23
  • 2
    Also explained here: http://stackoverflow.com/questions/13440375/invoking-virtual-method-in-constructor-difference-between-java-and-c – jas Apr 12 '15 at 16:25
  • 1
    @jas that's a nice close candidate. Voting to close as duplicate. – Benjamin Gruenbaum Apr 12 '15 at 16:28
  • @jas Thanks for giving the original question, I searched it but was not able to find it, hence asked. Closing the question. – Neetesh Dadwariya Apr 14 '15 at 03:13

0 Answers0