www.digitalmars.com         C & C++   DMDScript  

digitalmars.D - inheritance and override conflict

reply GM <GM_member pathlink.com> writes:
I started learning D to day. In playing around I found this behavior which
seemed a little strange to me. As you can see below the Writer class has two
prints. If I override one of them in WordWriter then I can no longer see the
other without implicitly calling super. If I call writer.print("Yikes") in main
as below compilation fails because Writer.print(char[]) is no longer visible.



import std.stdio;

class Writer {
static this() {
x = 1;
y = 2;
z = 3;
}

this() {
writefln(x, y, z);
}

~this() {
writefln(z, y, x);	
}

void print(char[] o) {
writef(o);
}

abstract void print(char o) {
writef(o);
}
private:
static const int x, y, z;	
}

class WordWriter : Writer {
this() {
writefln("go");
}

~this() {
writefln("and");	
}

void printWords(char[] str) {
foreach(char c; str) {
if(c == ' ')
super.print("\n");
else
print(c);		
}

super.print("\n");	
}

override:
void print(char o) {
super.print(o);
}	
}

void main() {
char[] str = "Hello, World!"; 
void delegate(char[]) f;

WordWriter writer = new WordWriter();
f = &writer.printWords;

writer.print("Yikes");

f(str);
}
May 25 2006
parent "Jarrett Billingsley" <kb3ctd2 yahoo.com> writes:
"GM" <GM_member pathlink.com> wrote in message 
news:e559gn$glk$1 digitaldaemon.com...
I started learning D to day. In playing around I found this behavior which
 seemed a little strange to me. As you can see below the Writer class has 
 two
 prints. If I override one of them in WordWriter then I can no longer see 
 the
 other without implicitly calling super. If I call writer.print("Yikes") in 
 main
 as below compilation fails because Writer.print(char[]) is no longer 
 visible.
Change the definition of WordWriter to the following: class WordWriter : Writer { this() { writefln("go"); } ~this() { writefln("and"); } void printWords(char[] str) { foreach(char c; str) { if(c == ' ') super.print("\n"); else print(c); } super.print("\n"); } alias Writer.print print; override void print(char o) { super.print(o); } } Notice the "alias Writer.print print." This brings the "super" version of the print method into the namespace of the WordWriter class, so that it overloads with the other methods. Also notice that if you were to put a colon after "override" it would make it apply to all subsequent method (and member) declarations, which might not be what you want. Notice in my version that it only affects the "void print(char o)" declaration.
May 25 2006