By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
449,220 Members | 1,588 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 449,220 IT Pros & Developers. It's quick & easy.

Issue with storing Parent/Child class in map

P: 22
I've a class 'Parent'

I declare a map using
map<Parent, Parent> mymap;

Now I derive one child 'Child'
and I've to add it to this map, so I do a static_cast like this:
Child* key = new Child();
Child* val = new Child();
mymap.insert(pair<Parent, Parent>(static_cast<Parent&>(*key), static_cast<Parent&>(*val)));

Now mymap shows correct count, but it doesn't find anything.

I search by creating another Child object and sending it as key like this:
Child key;
map<Parent, Parent>::iterator iter = mymap.find(key);

I've overloaded < operator for Parent class.
Every child object has a char* in it.
There is no copy-constructor defined for Parent class.

I need to know if mymap is storing objects then why they are not searchable.
This is urgently required, please help.
Thanks
Oct 20 '07 #1
Share this Question
Share on Google+
2 Replies


sicarie
Expert Mod 2.5K+
P: 4,677
jeet232-

I've renamed your thread title to actually describe your issue as outlined in our Posting Guidelines . (Did you know that properly titled threads actually get more traffic than those titled "URGENT help needed now!"?)
Oct 20 '07 #2

weaknessforcats
Expert Mod 5K+
P: 9,197
Child* key = new Child();
Child* val = new Child();
mymap.insert(pair<Parent, Parent>(static_cast<Parent&>(*key), static_cast<Parent&>(*val)));
What are you doing??? This looks like nonsense.

key and val are child objects. They can never be Parent Objects. Your cast is terribly destructive. It tells the compiler to disregard that fact that you have a Child object and to make a copy of it as a Parent object thereby shopping off all the Child atrributes and member functions. Slicing is a big no-no.

Substituting a Child for a Parent only works in you use a Parent pointer or reference. That would mean your map has to contain Parent pointers or references.

Also, the map uses the first member of the pair as a key and the second member as the value. I can see where the Parent (pointer or reference) might be a value but I don't see how it can also be a key.

Considering the map has its own tree structure, what are you doing with your own Child/Parent??

And I'm not sure you even have a Child class since the Child of a Parent is also a Parent to another child. In effect, they are both Parents.
Oct 21 '07 #3

Post your reply

Sign in to post your reply or Sign up for a free account.