covariant

Differing return type for virtual functions

落爺英雄遲暮 提交于 2019-11-29 09:37:24
A virtual function's return type should be the same type that is in base class, or covariant. But why do we have this restriction? Because of the nonsense that would ensue: struct foo { virtual int get() const { return 0; } }; struct bar : foo { std::string get() const { return "this certainly isn't an int"; } }; int main() { bar b; foo* f = &b; int result = f->get(); // int, right? ...right? } It isn't sensible to have a derived class return something completely unrelated. Because how would the code that's using the return value cope with all sorts of unrelated types coming back? e.g.: class

c# covariant generic parameter

元气小坏坏 提交于 2019-11-28 17:50:34
I'm trying to understand this but I didn't get any appropriate results from searching. In c# 4, I can do public interface IFoo<out T> { } How is this different from public interface IFoo<T> { } All I know is the out makes the generic parameter covariant (??). Can someone explain the usage of <out T> part with an example? And also why is applicable only for interfaces and delegates and not for classes? Sorry if it's a duplicate and close it as such if it is. Eric Lippert Can someone explain the usage of the out T part with an example? Sure. IEnumerable<T> is covariant. That means you can do