0

My class inherits from a map object:

This is the method I am trying to implement:

double MyCustomClass::returnValueForKey(string key){
    return this->find(key); //<--- No Viable conversion from iterator
}

How can I get something like this to work?

dhint4
  • 1,132
  • 2
  • 11
  • 25
  • 3
    It's a very bad idea to extend off standard containers. – PDizzle745 Jan 28 '15 at 20:42
  • I absolutely dislike the way C++ names some of its methods. It makes it much easier for the user to understand what is trying to happen. – dhint4 Jan 28 '15 at 20:45
  • What if I made this CustomClass just a normal object and then added a map to it and then implemented my methods this way? – dhint4 Jan 28 '15 at 20:46

2 Answers2

2

To solve the mechanical problem of getting the code to compile you would simply need to dereference the resulting iterator:

return find(key)->second;

Of course this is a bad solution because the question itself begins from a position where we have already made bad choices.

  1. Why not simply use the [] operator instead of this custom code?
  2. Why even derive from std::map in the first place? This is a bad idea and whatever the problem is, there are almost certainly better ways to solve it.
  3. Even if this code were correct, what happens when key does not exist in the map?
Community
  • 1
  • 1
Jon
  • 428,835
  • 81
  • 738
  • 806
  • Thanks for your post John. I am not going to extend off the map class. But to answer your question for number three, this method only gets executed if the key exists. – dhint4 Jan 28 '15 at 20:48
1

If the Map object you are talking about is std::Map it would be a much better idea to make an std::Map object a member of your MyCustomClass and extend the functionality this way.

Aside from some design reasons that could be considered subjective, the real sin here would be to extend a class that does not have a virtual destructor.

This would mean that when you call delete on one of your MyCustomClass objects the destructor of the parent class would never be called.

OlivierLi
  • 2,798
  • 1
  • 23
  • 30