The difference between these two 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 leads to the output:

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

JAVA Code:

 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 only produces

 B B 

Why is this conclusion different in this case?

+5
source share
2 answers

The difference lies in the processing of polymorphism during construction. In Java, the dynamic type of an object immediately refers to a derived class, which allows you to call a member function before the constructor can set member variables. This is bad.

C ++ has a different approach: at runtime, the type of an object is considered one of the classes to which the constructor belongs. All calls to member functions are resolved statically in accordance with this assumption. Therefore, constructor A calls A::foo() , and constructor B calls B::foo() .

+5
source

Edit

The first part of my answer was provided before the Java Testa constructor was added.


In Java code, you do not have the Testa constructor defined as in your C ++ code. This explains why only one B is printed in Java.

But even if you did it to make the code more equivalent:

 public Testa() { this.Foo(); } 

He will print

 B B 

Because in polymorphism, Java works even when calling a method from the constructor. But this is not a good idea, because the Testb object will still be uninitialized when the Foo method is called in Testb .

+2
source

Source: https://habr.com/ru/post/1204861/


All Articles