Possible Duplicate:
Conversion between Derived** to Base**
I'm getting back into C++ after several years of mostly Python, and am hitting up against a strongly-typed wall. I think I have a good handle on basic polymorphism and type-casting between pointers of base and derived classes (e.g. Can a pointer of a derived class be type cast to the pointer of its base class?), but here's a stumper: why can't I assign a pointer to a pointer to a derived class to a p-to-p to it's base class?
For more context (and perhaps tips on doing this less pythonishly), here's a reduced version of what I'm trying to do. I want to have a list of pointers to objects (derived from a single class) and a string identifying them (i.e. a map<string, obj*>
). A set of components will then pass a list of identifying strings and locations to store a pointer to the corresponding object (i.e. a map<string, obj**>
). I should then be able to find the appropriate object by its string id, and fill in the appropriate pointer for subsequent use by the component.
Simplified code to do this is
#include <map>
#include <string>
using namespace std;
class base
{
};
class derived: public base
{
};
typedef map<string, base**> BasePtrDict;
typedef map<string, base*> BaseDict;
int main(int argc, char* argv[])
{
base b1, b2;
derived d;
derived* d_ptr;
BaseDict base_dict;
base_dict["b1"] = &b1;
base_dict.insert(make_pair("b2",&b2)); // alternate syntax
base_dict["d"]= &d;
BasePtrDict ptr_dict;
ptr_dict["d"] = &d_ptr;
for (auto b = ptr_dict.begin(); b != ptr_dict.end(); b++)
*(b->second) = base_dict[b->first];
return 0;
}
This runs into a compile error at ptr_dict["d"] = &d_ptr;
. Why? In the C++ paradigm, what should I be doing? Do I really need to do ugly (unsafe?) reinterpret_cast<base>()
everywhere?