Using virtual functions to draw figures, does this make sense?

The book I'm using wants me to make a Figure class that has functions erase() draw() and center(). Then it has the subclasses Rectangle and Triangle.

The first step is to make all three classes so that they have all the necessary methods that simply output which class is being used and what function it is calling. Then the methods need to be changed to virtual methods.

The next step is to actually make the functions do something. That's where my issue is. It doesn't seem like I'm actually using the virtual functions the way that I'm supposed to. It just seems like I'm doing it the exact same way that I would were I just to overload the functions.

Figure class
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
class Figure
{
public:
    Figure();
    virtual void erase();
    virtual void draw();
    virtual void center();
private:
    bool cent;
};

Figure::Figure() : cent(false)
{

}

void Figure::erase()
{
    cout << "Figure class calling erase().\n";
}

void Figure::draw()
{
    cout << "Figure class calling draw().\n";
}

void Figure::center()
{
    cout << "Figure class calling center().\n";
    erase();
    cent = true;
    draw();
}


Rectangle class
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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
class Rectangle : public Figure
{   
public:
    Rectangle();
    void erase();
    void draw();
    void center();
private:
    void centerOutput();
    bool cent;
};

Rectangle::Rectangle() : Figure()
{
    
}

void Rectangle::erase()
{
    cout << "Rectangle class calling erase().\n\n";
}

void Rectangle::draw()
{
    for(int i = 0; i < 5; i++)
    {
        if(cent)
            centerOutput();
        
        cout << "*";
        for(int j = 0; j < 20; j++)
        {
            cout << "*";
        }
        cout << "*\n";
    }
}

void Rectangle::center()
{
    cout << "Rectangle calling center().\n";
    erase();
    cent = true;
    draw();
}

void Rectangle::centerOutput()
{
    const int l = 20;
    const int line = 80;
    int position = (int)((line - l) / 2);
    for(int i = 0; i < position; i++)
    {
        cout << " ";
    }
}
Topic archived. No new replies allowed.