Upcasting through a pointer

closed account (jwC5fSEw)
I'm learning about polymorphism. Here's the code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#include <iostream>
using namespace std;

class Shape {
  public:
    virtual void 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.
Last edited on
closed account (jwC5fSEw)
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!
Topic archived. No new replies allowed.