digitalmars.D.bugs - Subclasses in ()?():() statements
- "Thomas Kuehne" <thomas-ThisIsSpam kuehne.cn> Jun 07 2004
- "The Dr ... who?" <thedr who.com> Jun 13 2004
// the classes:
private class Master{}
private class Foo : Master{}
private class Bar : Master{}
public static int main(char[][] args){
bit isBar;
bit isFoo;
// valid and compiles:
Master a = (isBar) ? (new Bar()) : (new Master());
Master b = (isFoo) ? (new Foo()) : (new Master());
// valid, but fails to compile:
Master c = (isBar) ? (new Bar()) : (new Foo());
return 0;
}
Jun 07 2004
"Thomas Kuehne" <thomas-ThisIsSpam kuehne.cn> wrote in message news:ca1m8u$2ogp$1 digitaldaemon.com...// the classes: private class Master{} private class Foo : Master{} private class Bar : Master{} public static int main(char[][] args){ bit isBar; bit isFoo; // valid and compiles: Master a = (isBar) ? (new Bar()) : (new Master()); Master b = (isFoo) ? (new Foo()) : (new Master()); // valid, but fails to compile: Master c = (isBar) ? (new Bar()) : (new Foo());
This is not valid. The semantics of the ternary operator stipulate that the expression as a whole has the type of the second sub-expression. Hence, your statement is exactly equivalent to Master c = (isBar) ? cast(Bar)(new Bar()) : (new Foo()); which is obviously not valid. The fix is obvious Master c = (isBar) ? cast(Master)(new Bar()) : (new Foo());
Jun 13 2004








"The Dr ... who?" <thedr who.com>