I'm trying to teach myself C++, and one of the traditional "new language" exercises I've always used is to implement some data structure, like a binary tree or a linked list. In Java, this was relatively simple: I could define some class Node that maintained an instance variable Object data
, so that someone could store any kind of object in every node of the list or tree. (Later I worked on modifying this using generics; that's not what this question is about.)
I can't find a similar, idiomatic C++ way of storing "any type of object." In C I'd use a void
pointer; the same thing works for C++, obviously, but then I run into problems when I construct an instance of std::string
and try to store it into the list/tree (something about an invalid cast from std::string&
to void*
). Is there such a way? Does C++ have an equivalent to Java's Object (or Objective-C's NSObject)?
Bonus question: If it doesn't, and I need to keep using void pointers, what's the "right" way to store a std::string
into a void*
? I stumbled upon static_cast<char*>(str.c_str())
, but that seems kind of verbose for what I'm trying to do. Is there a better way?