C++ is bad: problems with the ternary operator, addendum

Apr 11, 2008 02:44

I've found another interesting wrinkle in the ternary operator. So, here's a bonus question for that quiz from last time. You start with the following code:class Abstract;
class DerivedOne; // Inherits from Abstract
class DerivedTwo; // Inherits from Abstract
Abstract x;
DerivedOne one;
DerivedTwo two;
bool test;
Again, you can assume that all of these are defined/initialized (and you can assume the comments are correct-both Derived* classes inherit from Abstract). Now, consider these snippets:

Question
NumberCode Snippet
ACode Snippet
BBonusif (test) x = one;
else x = two;x = (test ? one : two);
If you read the previous installment, you've probably guessed by now that these are not equivalent, and you'd be right. In what ways do they differ?



Do you have an answer? Better double check that.

Alright, time's up. It's a little bit of a trick question. Snippet B does not compile! Instead, it fails with an error: no match for ternary 'operator?:' in 'test ? one : two' (at least, that's what it says in GCC; your error message may be different). Section 5.16 of the C++ Standard states that the ternary operator will only work if, of the two values that can be returned, one is a subclass of the other (or one is an exception that gets thrown, or a couple other things like that). In other words, snippet B is not valid because DerivedOne is not a subclass of DerivedTwo or vice versa, regardless of whether they share a superclass. As before, I feel that this goes against the Principle of Least Surprise, and it bugs me.

ternary, code, software, ternary operator, cpp, cpp is bad, computer science

Previous post Next post
Up