Changing class type to a derived class - possible?

May 6, 2016 at 2:32pm
I was wondering if it was possible to change the class of an object to something derived from it, and if so how would be best to do it?

For example, I have an abstract base class called polygon, and derived classes such as triangle, quadrilateral etc, which contain a vector of pairs that are the coordinates of their vertices. I would like to have a class for squares, derived from quadrilateral, but is there a way of changing an object's class from quadrilateral to square (after checking that the quadrilateral is a square of course)?

I've been reading here (http://www.cplusplus.com/doc/tutorial/typecasting/) about static_cast but I can't really get my head around it. Does this only work in the case of pointers?

Thanks!
May 6, 2016 at 3:30pm
You may want to look into dynamic_cast<>(). However, what you are trying to do suggests a design flaw; if you are putting all these polygons into a list, you should treat them as polygons. If you want to handle them in special ways based on their actual type either use polymorphism or actually handle them separately.
May 6, 2016 at 8:16pm
Ahh yes, sorry if I wan't clear before, I am using polymorphism already. I'll look into dynamic_cast, thanks.
May 6, 2016 at 8:29pm
If you need to cast to a more specific type, you aren't using polymorphism anymore. If you were using polymorphism, you would call a method on polygon that was overridden to do the proper thing for whatever type you were actually working with.
Last edited on May 6, 2016 at 8:29pm
Topic archived. No new replies allowed.