How to know the type of an object in a list?
Posted
by
nacho4d
on Stack Overflow
See other posts from Stack Overflow
or by nacho4d
Published on 2010-12-26T19:03:53Z
Indexed on
2010/12/26
21:54 UTC
Read the original article
Hit count: 160
Hi,
I want to know the type of object (or type) I have in my list so I wrote this:
void **list; //list of references
list = new void * [2];
Foo foo = Foo();
const char *not_table [] = {"tf", "ft", 0 };
list[0] = &foo;
list[1] = not_table;
if (dynamic_cast<LogicProcessor*>(list[0])) { //ERROR here ;(
printf("Foo was found\n");
}
if (dynamic_cast<char*> (list[0])) { //ERROR here ;(
printf("char was found\n");
}
but I get :
error: cannot dynamic_cast '* list' (of type 'void*') to type 'class Foo*' (source is not a pointer to class)
error: cannot dynamic_cast '* list' (of type 'void*') to type 'char*' (target is not pointer or reference to class)
Why is this? what I am doing wrong here? Is dynamic_cast what I should use here?
Thanks in advance
EDIT:
I know above code is much like plain C and surely sucks from the C++ point of view but is just I have the following situation and I was trying something before really implementing it:
I have two arrays of length n but both arrays will never have an object at the same index. Hence, or I have array1[i]!=NULL or array2[i]!=NULL. This is obviously a waste of memory so I thought everything would be solved if I could have both kind of objects in a single array of length n.
I am looking something like Cocoa's (Objective-C) NSArray where you don't care about the type of the object to be put in. Not knowing the type of the object is not a problem since you can use other method to get the class of a certain later. Is there something like it in c++ (preferably not third party C++ libraries) ?
Thanks in advance ;)
© Stack Overflow or respective owner