digitalmars.D - Re: Old problem with performance
- Kagamin <spam here.lot> Feb 10 2009
- Michel Fortin <michel.fortin michelf.com> Feb 10 2009
Weed Wrote:Well, D class code here is not equivalent to C++ class code. D code has more features, namely, it's polymorphic: C.opAdd is able to work with classes, derived from C, while corresponding C++ code is unable to do so.
I am do not agree with you: // C++: class C { public: virtual void doSomething( C src ) {} }; class C2 : public C { }; int main( int argc, char* argv[] ) { C c; C2 c2; c.doSomething( c2 ); return 0; }
Well, you can pass descendant objects :) I was surprised by this destructive feature. But code is still not polymorphic. Consider the following code: class C { public: virtual char* doSomething( C src ) { return src.Method(); } virtual char* Method() { return "It's C."; } }; class C2 : public C { public: virtual char* Method() { return "It's C2."; } }; int main(void) { C c; C2 c2; printf("%s\n",c.doSomething(c)); printf("%s\n",c.doSomething(c2)); return 0; } What do you think is its output?
Feb 10 2009
On 2009-02-10 08:02:31 -0500, Kagamin <spam here.lot> said:Well, you can pass descendant objects :) I was surprised by this destructive feature. But code is still not polymorphic. Consider the following code: class C { public: virtual char* doSomething( C src ) { return src.Method(); } virtual char* Method() { return "It's C."; } }; class C2 : public C { public: virtual char* Method() { return "It's C2."; } }; int main(void) { C c; C2 c2; printf("%s\n",c.doSomething(c)); printf("%s\n",c.doSomething(c2)); return 0; } What do you think is its output?
Since you're passing c2 as a C by value to doSomething, slicing do occur and it prints "It's C." two times. That's why in C++ we generally pass objects by reference. Unfortunately, you often can't do that for return values.. -- Michel Fortin michel.fortin michelf.com http://michelf.com/
Feb 10 2009