C++ list of mixed classes
Hello
I have some classes like so: class node { //data and functions } class specific : public node { aFunction(); } class specific2 : public node { anotherFunction(); } and I have a list of pointers to objects of class node: list<node *> node_list; but all these objects are in fact a mixture of class specific and specific2, as they both inherit from class node. I wish to iterate through my list and call aFunction() or anotherFunction() based on what type my node actually is. How do I: tell what type my node is? subsequently call the correct function? Thanks Martin |
Well do you need to know what type it is? do you need to call different functions?
As they both inhert from node you could use polymorphism, if do don't know what this is just do a quick google. You could also try casting down(ie from node to specific or specific2. checking the value) but this is normal evidence of bad design. |
Preferably you can rename anotherFunction() to aFunction() also and make a virtual aFunction() in node, so that you can call aFunction() for any "node" and it will call the right one and then you don't have to tell which type it is.
|
here is an example of what dmail was saying..
Code:
#include <iostream> in Foo in FooBar in FooBaz notice how the test function just requires a Foo, and then from the base Foo it finds the correct function for the object that it was passed.. isnt c++ great. :) and as was suggested read up on polymorphism.. |
Quote:
ta0kira |
Quote:
|
To literally do what martinrp asked, you can use dynamic_cast -- google for it. But the others are right; it looks like you should use polymorphism instead.
|
Quote:
ta0kira PS dynamic_cast is also dependent on RTTI, which increases your overhead... |
Quote:
Quote:
<edit> correction Quote:
|
ta0kira: the OP said he didn't know what types the node*s were pointing to. dynamic_cast can figure that out; it returns null if you guess the wrong one. static_cast can't figure that out; it only knows what you tell it.
|
Quote:
Quote:
I suppose I have just never been a fan of dynamic_cast; I think it's one of those things like reinterpret_cast that should be avoided whenever possible. Here is the scenario I picture; you have a heterogenous list, and every operation on an element starts by seeing the element as the base class. At a certain point, the operation will decide which derived class the element is, and at that point will cast it and perform an operation on it. This can all be easily avoided by creating an extra virtual function, thereby avoiding all casts, and also allowing the addition of other derived classes without adding additional casts. ta0kira |
Quote:
ta0kira |
All times are GMT -5. The time now is 03:02 AM. |