Ternary Operator and Polymorphism

Started by
2 comments, last by taurusrow 10 years, 12 months ago

Simplified question : Can I use the ternary operator in a new object declaration.

For example, if I have a two player game, and depending on whose turn it is:

classA { ... }

classB : classA {...}

classC : classA {...}

classA _Object = ((_turn % 2 == 0) ? new classB : new classC);

When I do this, I'm told that the operands are incompatible. I could have sworn that I've seen this working before, but I can't seem to get it to work. I tried restructuring and had the same results with this:

classA { ... }

classB : classA {...}

classC : classA {...}

classB cb;

classC cc;

classA _Object = ((_turn % 2 == 0) ? cb : cc);

Any insight would be appreciated. Thanks!

Advertisement

In the first case it looks like you're trying to assign a pointer to a class to a non-pointer variable type.

In the second case your operands are definitely different types (and anyway, you're assigning to a variable of the type of the parent class, which will cause slicing)

(Is this your actual code?)

If you're trying to assign to a pointer to classA, like the following:

classA *_Object = ((_turn % 2) == 0) ? new classB : new classC);

Then you can get it to work by static_cast'ing each of the operands to A*.

Then you can get it to work by static_cast'ing each of the operands to A*.

That is right. Although a conversion from a pointer to a derived class to a pointer to its base class is implicit, the rules for the ternary operator are such that you need to explicitly cast at least one of them, so the compiler can deduce the type that the ternary operator will return:
  Base *b = (turn % 2 == 0) ? static_cast<Base *>(new Derived1) : static_cast<Base *>(new Derived2);

Thanks for your replies.

@Phil - it wasn't my actual code, I simplified, but it was the basic idea that I couldn't get to work. The second attempt was based on something I read in another forum and didn't think would work as it was (turns out I was right).

@Alvaro - thanks for the sample code. At first I wasn't getting it to work, then realized that I wasn't static casting to a pointer of the base class.

Sometimes one needs to really stop looking at code, then come back with a fresh mind. Appreciate the help! Thanks.

This topic is closed to new replies.

Advertisement