Stroustrup is disappointed with D :(
Ali Çehreli via Digitalmars-d
digitalmars-d at puremagic.com
Tue Sep 22 12:38:34 PDT 2015
On 09/22/2015 11:58 AM, Tourist wrote:
> "D disappointed me so much when it went the Java way".
> https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#to-do-unclassified-proto-rules
>
>
> It's something about virtual calls, but I didn't understand what he
> means. What does he mean?
It is about virtual calls in ctors and dtors. Here is the problem:
import std.stdio;
class B {
this() {
foo();
}
void foo() {
writeln("base");
}
}
class D : B {
this() {
writeln("derived is only now complete");
}
override void foo() {
writeln("derived");
}
}
void main() {
auto b = new D;
}
Although we are in the middle of consructing a D, the call foo() inside
B's ctor is dispatched to D's virtual foo() even though the D part of
the object has not been constructed yet. This is in contrast to C++,
where the object goes through multiple personalities during its
construction: First B, then D, etc.
The program above prints
derived
derived is only now complete
As can be seen, D.foo is called before D is ready for use.
Here is the equivalent C++ program:
#include <iostream>
using std::cout;
class B {
public:
B() {
foo();
}
virtual ~B() {}
virtual void foo() {
cout << "base\n";
}
};
class D : public B {
public:
D() {
cout << "derived is only now complete\n";
}
virtual void foo() {
cout << "derived\n";
}
};
int main()
{
D d;
}
The output of the C++ program:
base
derived is only now complete
C++'s approach is better from the point of view of corretness. However,
it is slower because the object's vtbl pointer must be stamped several
times during construction. (I am not aware of available compiler
optimizations there.)
Ali
More information about the Digitalmars-d
mailing list