Newbie: copy, assignment of class instances
bearophile
bearophileHUGS at lycos.com
Thu May 27 13:29:31 PDT 2010
Larry Luther:
>Ok, I've added -w to compilation commands and I've switched back to pure text.<
Good :-)
>What am I missing?<
I have modified a bit your D code like this, to have something with a main() that runs:
import std.c.stdio: puts;
class A {
int x, y;
void copy(const A a) {
puts("A copy");
x = a.x;
y = a.y;
}
}
class B : A {
int z;
void copy(const B b) {
puts("B copy");
super.copy(b);
z = b.z;
}
}
void main() {
A a1 = new A;
A a2 = new A;
B b1 = new B;
B b2 = new B;
a1.copy(a2); // should execute A.copy
a1.copy(b1); // should execute A.copy
b1.copy(b2); // should execute B.copy
b1.copy(a1); // should execute A.copy
}
I have also translated your the code to Java, because sometimes Java designers are more "correct" thant D designers:
class A {
int x, y;
void mycopy(A a) {
System.out.println("A mycopy");
x = a.x;
y = a.y;
}
}
class B extends A {
int z;
void mycopy(B b) {
System.out.println("B mycopy");
super.mycopy(b);
z = b.z;
}
public static void main(String[] args) {
A a1 = new A();
A a2 = new A();
B b1 = new B();
B b2 = new B();
a1.mycopy(a2); // should execute A.mycopy
a1.mycopy(b1); // should execute A.mycopy
b1.mycopy(b2); // should execute B.mycopy
b1.mycopy(a1); // should execute A.mycopy
}
}
The Java code compiles and runs with no errors, and prints:
A mycopy
A mycopy
B mycopy
A mycopy
A mycopy
But the D version is different. It seems you have found a small difference between Java and D that I didn't know about.
If I comment out the last line of the main() in the D code (b1.copy(a1);) and I compile the D code with -w it generates the warning I was talking about:
test.d(13): Error: class test.B test.A.copy(const const(A) a) is hidden by B
If I leave that line uncommented then the compilation stops with a different error:
test.d(33): Error: function test.B.copy (const const(B) b) is not callable using argument types (A)
test.d(33): Error: cannot implicitly convert expression (a1) of type test.A to const(B)
It seems in D the copy() of B replaces (hides) the copy() of A, even if no override is used. I don't know why D is designed this way, it can even be a design/implementation bug. But the presence of that warning suggests me this is expected, so it's probably just a difference between Java and D. If no one answers to this here then maybe later I will ask about this in the main D group.
Bye,
bearophile
More information about the Digitalmars-d-learn
mailing list