Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between these 2 codes?

I was wondering why this piece of JAVA code produces a different output than the same code in C++.

#include "stdafx.h"
#include <iostream>
using namespace std;

class A
{
public: 
    A(){
        this->Foo();
    }
    virtual void Foo()
    {
        cout << "A::Foo()" << endl;
    }
};
class B : public A
{
public:
    B()
    {
        this->Foo();
    }
    virtual void Foo()
    {
        cout << "B::Foo()" << endl;
    }
};
int main(int, char**)
{
    B objB;
    system("pause");
    return 0;
}

This produces the output:

A::Foo()
B::Foo()

The JAVA code is:

public class Testa {
    public Testa()
    {
        this.Foo();
    }
    public static void main(String[] args) 
    {
        Testb b = new Testb();
    }
    void Foo()
    {
        System.out.println("A");
    }

}
class Testb extends Testa {
    public Testb()
    {
        this.Foo();
    }
    @Override
    void Foo()
    {
        System.out.println("B");
    }
}

This code produces only

B
B

Why is this output different in this case?

like image 326
Matt Jones Avatar asked Oct 16 '14 19:10

Matt Jones


1 Answers

The difference is in the handling of polymorphism during construction. In Java, the dynamic type of the object is that of the derived class right away, allowing you to call member function even before the constructor gets a chance to set the member variables. This is bad.

C++ has a different approach: While the constructor runs, the type of the object considered to be the one of the class that the constructor belongs to. All calls to member functions are resolved statically according to that assumption. Consequently, the constructor of A calls A::foo(), while the constructor of B calls B::foo().

like image 63
cmaster - reinstate monica Avatar answered Sep 27 '22 23:09

cmaster - reinstate monica