• Advertisement
Sign in to follow this  

Ternary Operator and Polymorphism

This topic is 1731 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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!

 

Share this post


Link to post
Share on other sites
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*.

Share this post


Link to post
Share on other sites

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.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement