Click to See Complete Forum and Search --> : Error when trying to dynamic_cast<> a reference of a variable


johnnyICON
March 13th, 2005, 01:41 AM
Hi, I am trying to create a function that compare's two objects.

Here, take a look:
int Integer::compareTo(const NodeItem &anotherNodeItem)
{
int returnCode = 0;

Integer *otherInteger = dynamic_cast<Integer&>(anotherNodeItem);

if (otherInteger == NULL)
returnCode = ERROR_INCOMPATIBLE_TYPES;
else
returnCode = compareTo(*otherInteger);

delete otherInteger;

return returnCode;
}

The error I get when I try to compile is at this statement:
Integer *otherInteger = dynamic_cast<Integer&>(anotherNodeItem);

The error is this:
Integer.cpp(54): error C2682: cannot use dynamic_cast to convert from 'const NodeItem' to 'Integer &'

I'm not too sure of another way of doing this, but basically I want the function to be able to take a NodeItem pointer, and check whether the NodeItem is an Integer by using dynamic_cast and testing for a NULL result.

Thanks for the help in advance.

Ajay Vijay
March 13th, 2005, 03:02 AM
First Integer *otherInteger = dynamic_cast<Integer&>(anotherNodeItem);'&' should be '*'
Second, please tell what's the relation between NodeItem and Integer types?

johnnyICON
March 13th, 2005, 04:31 PM
An Integer is a NodeItem.

A NodeItem is an abstract class for any piece of data that is in a node.

johnnyICON
March 13th, 2005, 04:34 PM
Integer *otherInteger = dynamic_cast<Integer*>(anotherNodeItem);
error C2682: cannot use dynamic_cast to convert from 'const NodeItem' to 'Integer *'

Graham
March 13th, 2005, 04:37 PM
Point 1: you can't remove constness with dynamic_cast: you will need to cast to const Integer&

Point 2: you're trying to assign it to a pointer to integer. Either change the variable declaration to const Integer& or change the cast to dynamic_cast<const Integer *>(&anotherNodeItem) (and make the variable const).

johnnyICON
March 13th, 2005, 06:26 PM
Thanks, it worked.

const Integer *otherInteger = dynamic_cast<const Integer*>(&anotherNodeItem);

johnnyICON
March 13th, 2005, 09:52 PM
Something I didn't notice, but there is a warning message with that comes with that statment:
warning C4541: 'dynamic_cast' used on polymorphic type 'NodeItem' with /GR-; unpredictable behavior may resultI'm just wondering if it means anything other than what I can understand as unpredictable behaviour.

Kheun
March 13th, 2005, 11:07 PM
See MSDN (http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vccore98/html/c4541.asp). You have to turn on RTTI in order to use dynamic_cast<>.