Shape drawings
Create a base class Shape with a method draw() that outputs "Drawing a generic shape." Create a derived class Circle that overrides the draw() method to output "Drawing a circle."
- Create a
Shapepointer and make it point to aCircleobject. - Call the
draw()method using this pointer. - Observe and explain the output.
Hint
Remember that the method called is determined by the type of the pointer, not the type of the object it points to.
Answer
#include <iostream>
class Shape {
public:
void draw() {
std::cout << "Drawing a generic shape." << std::endl;
}
};
class Circle : public Shape {
public:
void draw() {
std::cout << "Drawing a circle." << std::endl;
}
};
int main() {
Shape* shapePtr = new Circle();
shapePtr->draw(); // Output will be "Drawing a generic shape."
delete shapePtr; // Clean up memory
return 0;
}
Explanation: The draw() method from the Shape class is called because the pointer shapePtr is of type Shape*, even though it points to a Circle object.
Part 2
Using the code you just created, cast shapePtr to a Circle* before calling draw from it and observe the difference.
Part 2 Answer
int main() {
Shape* shapePtr = new Circle();
shapePtr->draw(); // Output will be "Drawing a generic shape."
delete shapePtr; // Clean up memory
return 0;
}
Because draw is called from a Cicle pointer, it calls Circle::draw.