• Create Account

## Ternary Operator and Polymorphism

Old topic!

Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

3 replies to this topic

### #1taurusrow  Members

119
Like
0Likes
Like

Posted 23 April 2013 - 10:24 PM

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!

### #2phil_t  Members

7654
Like
1Likes
Like

Posted 23 April 2013 - 11:12 PM

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)

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*.

### #3Álvaro  Members

20272
Like
5Likes
Like

Posted 24 April 2013 - 08:37 AM

POPULAR

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);

### #4taurusrow  Members

119
Like
0Likes
Like

Posted 24 April 2013 - 07:36 PM

@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.

Old topic!

Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.