#include <iostream>
usingnamespace std;
class Shape {
public:
virtualvoid draw() const {
cout << "Drawing shape\n";
}
};
class Circle : public Shape {
public:
void draw() {
cout << "Drawing circle\n";
}
};
class Square : public Shape {
public:
void draw() {
cout << "Drawing square\n";
}
};
class Triangle : public Shape {
public:
void draw() {
cout << "Drawing triangle\n";
}
};
int main() {
Shape* s[] = { new Circle, new Square, new Triangle };
for (int i = 0; i < 3; ++i) {
s[i]->draw();
}
return 0;
}
I thought this would call the overloaded draw() functions in each derived class. Instead, it calls the base class's draw(). I guess I don't fully understand upcasting, so what am I doing wrong?
You either need to get rid of the const on the draw function in the shape class
OR
add the const keyword to the functions in Circle, Square and Triangle.
They should either all have it, or none of them should have it.
Ohhh, I see. I'm not entirely solid on some elements of function overloading, and I didn't realize that const would differentiate the functions. I changed the derived classes' functions to const and it worked as it should, thanks!