[prog] C++: storing objects of different type in a std::map

Riccarda Cassini riccarda.cassini at gmx.de
Tue Sep 21 09:51:19 EST 2004


On Mon, Sep 20, 2004 at 08:22:49PM -0500, Kathryn Hogg wrote:
> 
> What you want to do is store an object that can be of type baseClass or
> any of its descendents.  C++ provides two constructs for this: pointers
> and references.
> 
> The simplest methos would be to change the map to
> 
>    std::map<std::string, baseClass *> dispatch;
> 
> and then allocate heap objects to put in the map.

Thanks very much, Kathryn.  Making use of the indirection did indeed
nicely solve my problem.  In other words, when I use the combination

    ...
    std::map<std::string, baseClass *> dispatch;
    ...
    dispatch["mode-A"] = new ClassA;
    ...
    dispatch["mode-A"]->update();

everything behaves as desired.  Two questions remain, though:

1) Why does the baseClass ever need to be instatiated at all, in the
version that I tried originally?  Does the map declaration

    std::map<std::string, baseClass> dispatch;

actually create an object of type baseClass?  If so, what is it for?

2) Why is it that the pointers ClassA* and ClassB* are not being cast
to baseClass*, while the derived objects themselves are obviously being
cast to type baseClass when being put in the map?  I mean, a pointer of
type ClassA* is different from a pointer of type baseClass*, just as
the type ClassA is not the same as type baseClass - so what's the logic
behind treating objects and pointers to objects differently?

Can this be explained somehow, or do I just have to take it as it is?
You know, as usual, I'm trying to understand the underlying concepts...

Riccarda



More information about the Programming mailing list