Contravariance (is this a bug)

Jesse Phillips jessekphillips+D at gmail.com
Mon Jul 26 09:46:57 PDT 2010


Contravariance allows derived classes to return from a function any derived class of what the parent class returns. I have discovered that if you claim to return a derived class, you can still return the parent class. In the example below, A_Parser is returning Report[] from a function that claims to return A_Report[]. I'm thinking this is a bug, is there any reason it wouldn't be?

import std.stdio;

class A_Parser : Parser {
   Report[string] stuff;

   this() {
      stuff = ["hi": new A_Report("Bye")];
   }

   override A_Report get(string uuid) {
      return stuff[uuid];
   }
}

class A_Report : Report {
   string value;
   this(string val) {
      value = val;
   }

   void print() {
      writeln(value);
   }
}

abstract class Parser {
   abstract Report get(string);
}

class Report {
}

void main() {
   auto a = new A_Parser();

   a.get("hi").print;

}



More information about the Digitalmars-d mailing list