I am reading Bjarne Stroustrup's book The C++ Programming Language, and in section 3.2.4, he demonstrates a class hierarchy, starting with an abstract class. His code looks something like this:
class Shape
{
public:
virtual Point center()const = 0; //Point is a class defined elsewhere and is unimportant for this question
virtual void move(Point to) = 0;
virtual void draw()const = 0;
virtual void rotate(int angle) = 0;
}
class Circle: public Shape
{
//overrides functions
}
void rotate_all(vector<Shape*>& v, int angle)
{
for(auto p:v)
p->rotate(angle);
}
My question is this: what type is the p
variable when the function rotate_all
is called with a vector of Circle
objects? If it was a Shape
, then wouldn't the objects be sliced into generic Shape
objects? If it was a Circle
, then wouldn't the function work only for vectors of Circle
objects, and not other subclasses of the Shape
class?
Aucun commentaire:
Enregistrer un commentaire