Error when trying to dynamic_cast<> a reference of a variable
Hi, I am trying to create a function that compare's two objects.
Here, take a look:
Code:
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:
Code:
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.
Re: Error when trying to dynamic_cast<> a reference of a variable
First
Code:
Integer *otherInteger = dynamic_cast<Integer&>(anotherNodeItem);
'&' should be '*'
Second, please tell what's the relation between NodeItem and Integer types?
Re: Error when trying to dynamic_cast<> a reference of a variable
An Integer is a NodeItem.
A NodeItem is an abstract class for any piece of data that is in a node.
Re: Error when trying to dynamic_cast<> a reference of a variable
Code:
Integer *otherInteger = dynamic_cast<Integer*>(anotherNodeItem);
error C2682: cannot use dynamic_cast to convert from 'const NodeItem' to 'Integer *'
Re: Error when trying to dynamic_cast<> a reference of a variable
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).
Re: Error when trying to dynamic_cast<> a reference of a variable
Thanks, it worked.
Code:
const Integer *otherInteger = dynamic_cast<const Integer*>(&anotherNodeItem);
Re: Error when trying to dynamic_cast<> a reference of a variable
Something I didn't notice, but there is a warning message with that comes with that statment:
Code:
warning C4541: 'dynamic_cast' used on polymorphic type 'NodeItem' with /GR-; unpredictable behavior may result
I'm just wondering if it means anything other than what I can understand as unpredictable behaviour.
Re: Error when trying to dynamic_cast<> a reference of a variable
See MSDN. You have to turn on RTTI in order to use dynamic_cast<>.