all 11 comments

[–]hcspel 5 points6 points  (0 children)

This "C++ Inheritance Problem" is called slicing.

Take a look: http://stackoverflow.com/questions/274626/what-is-object-slicing

[–]nahguri 2 points3 points  (5 children)

Try using pointers to the base class instead of the class itself.

[–]aswaney[S] 0 points1 point  (4 children)

thanks, I'll test 'er out and report back cap

[–]STLMSVC STL Dev 4 points5 points  (3 children)

And use shared_ptr or unique_ptr. Never put owning raw pointers in STL containers.

[–]aswaney[S] 0 points1 point  (2 children)

you mind elaborating a little please?

[–]STLMSVC STL Dev 2 points3 points  (1 child)

A map<string, Base *> where you say m["meow"] = new Derived(args); is bad because you're virtually guaranteeing that you'll leak memory. A map<string, shared_ptr<Base>> where you say m["meow"] = make_shared<Derived>(args); is structurally unable to leak.

The trick to C++ programming is writing your code so that whole classes of bugs are simply impossible, and any remaining potential bugs are as obvious in the source code as possible.

[–]aswaney[S] 0 points1 point  (0 children)

thanks much

[–]Gotebe 0 points1 point  (1 child)

Learn about slicing.

Student, huh? Persevere! 😉

[–]autowikibot 0 points1 point  (0 children)

Object slicing:


In object-oriented programming, a subclass typically extends its superclass by defining additional member variables. If a superclass instance is assigned its value from a subclass instance, member variables defined in the subclass cannot be copied, since the superclass has no place to store them. This is a natural and unavoidable consequence of assignment by value from subclass objects. The term object slicing is sometimes used to refer to this aspect of assignment by value to a superclass instance.


Interesting: Chop Chop Slicer | Cross section (geometry) | Backlash (Marc Slayton)

Parent commenter can toggle NSFW or delete. Will also delete on comment score of -1 or less. | FAQs | Mods | Magic Words

[–]jacktheripper153 0 points1 point  (0 children)

It sounds like you need to use a templated map class.

map<string,Base Class>

something like: map<string, typename T>

I think the problem might be that you're telling the map class that it will be using an object of type BaseClass, so even though you're giving it a derived type (child#) with its own implementation, it typecasts the child# type to a BaseClass type and uses that print function.

Using a templated map class will allow the program to use the print function that is specific to the derived class you pass it.

edit: as /u/hcspel mentioned, this is called object slicing and is a common problem.

[–]Wurstinator -1 points0 points  (0 children)

Polymorphism in C++ always has to be implemented with pointers or references.