This line won't compile:
Shape shape = (i % 2) ? Circle(5) : Rectangle(5, 5);
(I know it's useless since whatever the expression returns will be reduced to a simple Shape
, that's not the point).
Can't figure out why it won't compile. I'm creating a Shape
variable named shape
(which I think at this point creates a new Shape
), and then I'm assigning this variable the result of an expression. Why doesn't this compile?
The error:
no match for ternary operator
What's really weird is that the longer code with exact same meaning does compile and run as expected:
Shape shape;
if (i % 2)
shape = Rectangle(5, 5);
else shape = Circle(5);
Circle
andRectangle
both derived fromShape
, definitely slices. Avoid both slicing and solve your polymorphic ternary indiscretion by using something else such as smart pointers. (see it live). – Outdated