0

I have a map of base class pointers and I need to apply a class function to the mapped data.

I am dealing with shapes the user will input and then has the opportunity to manipulate them (translate, rotate...). I have functions witch work that manipulate the shapes and the shapes are stored in a map.

I am struggling with how to access and manipulate the mapped shapes.

I have the following code;

polygon * T;   
map<string, polygon*> shape_map;
new_shape = Trans + user_input;  // adds Tranaslated to the key

cout << "ID " << new_shape << " = " << endl;  // ouput the key witch also id's the shape
T = shape_map[user_input]->translate(matrix(Xtrans, Ytrans));  
T->printshape();

When I run my code the program stops just before it should print the shape and when I debug it highlights a line in my translate function, but I'm confident that my translate function is fine as I have tested it before.

I think the problem is in how I am calling the functions but I'm not certain.

Any help would be great!

Peter
  • 183
  • 1
  • 1
  • 6
  • 1
    I don't see where you placed new_shape in the map. I'm assuming you expect shape_map[user_input] to return new_shape. – Tony Lee Apr 22 '15 at 20:08
  • Yes sort of. I want to avoid adding the new translated shape to shape_map as I would like to show the user it and then ask if they would like to store the shape. – Peter Apr 23 '15 at 14:22
  • The translate function returns a type of whatever it acts on (the types of shape are derived classes from polygon which is an abstract base class). – Peter Apr 23 '15 at 14:30

1 Answers1

0

If there is no polygon in the shape dictionary stored under the key that's in user_input, shape[user_input] will return null. Assuming translate is not a virtual function, the program will crash when translate accesses 'this'. If it is virtual, it will crash when trying to call translate.

When the key isn't found, a map will construct a new <T>(), but in your case, T is simply a pointer and the default constructor for a pointer sets it to null.

Community
  • 1
  • 1
Tony Lee
  • 5,622
  • 1
  • 28
  • 45