Re: Type "assurance" of derived classes
On Aug 18, 10:02 am, Oliver Graeser <grae...@phy.cuhk.edu.hk> wrote:
Triple-DES wrote:
On 15 Aug, 09:16, Oliver Graeser <grae...@phy.cuhk.edu.hk> wrote:
Oliver Graeser <grae...@phy.cuhk.edu.hk> writes:
I'm coming from Java to C++ and this is one of the very
last problems I have so far... In Java, if I have, say, a
class SISNode that extends NetworkNode, I can have a
function that returns a NetworkNode but I can assure the
compiler that it is in fact a SISNode and therefore call
the method getStatus() that only a SISNode has. Like
SISnode s,t;
NetworkNode n;
n =t;
n.getStatus();//won't work
s= (SISNode) n;
s.getStatus(); //will work
This is supposed to be Java, I suppose.
Yes, it was supposed to be Java
The exact equivalent in C++ would be:
SISnode* s ;
SISnode* t ;
NetworkNode* n ;
n = t ;
n->getStatus() ; // won't work
s = dynamic_cast< SISnode* >( n ) ;
s->getStatus() ; // will work./
Thanks a lot for that! I will consider what Alf Steinbach wrote above =
on
how to do it with a boost::shared_ptr, but in any case this is exactly
what I was trying to do. The word "dynamic_cast" is actually the key, =
it
is really hard to google something when you don't know its name ;)
I'd just like to mention that if the dynamic type of *s happened to be
something else (not a SISnode), then this would not work. To ensure
that the cast succeeded, check the pointer against 0.
Thanks for the hint. I'm actually not worried about having nodes with
the wrong type since every network only has one kind of node, I'm going
through this ordeal only because I want to keep all reporting methods in
the same network class.
I used you hint though to work out another problem. I originally stored
all my nodes in an array, such as
GenericNetworkNode * nodeList;//declaration
.....
nodeList = new SISNetworkNode[size];//network constructor
.....
SISNetworkNode *snn;
snn=dynamic_cast <SISNetworkNode*> (&nodeList[i]);//here comes the disa=
ster
I managed to find out that it is something about the array, i.e. if I
instead use an array of pointers, create a node for each pointer, and
then do the dynamic cast for nodeList[i] instead of &nodeList[i], it
works. Is there any particular reason why dynamic casts doesn't work
with arrays?
s = dynamic_cast<SISnode*>(n);
if(!s)
{
// the cast failed, handle error...
}
or:
if( !(s = dynamic_cast<SISnode*>(n)))
{
// handle error...
}
I prefer the former.
DP- Hide quoted text -
- Show quoted text -- Hide quoted text -
- Show quoted text -
Oliver, your question is exactly about polymorphism.
polymorphism in C++ is implemented with Pointers and References. You
can't expect polymorphic behavior on objects.
And, since they SisNode and NetworkNode are in the same class
hierarchy, static_cast is supposed to use instead of dynamic_cast. The
latter is usually used in multi-inheritence casting a base to its
sibling. But it's so possible to be fail that Triple-DEC mentioned to
check the result of casting.