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?
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()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With