Simple classe question

Hi I'm new in c++

I create a class Shapes and child class Rectangle and Cercle. I want to be able to create as much as I want of these shape (ok maybe max 100). So I want to have all my shape in a contaner. Each time I create a shape it go on the contaner, but as I have Rectangle and Cercle I don't know how to put 2 different instance in one contaner?
Which contaner I need and who implement it?


Thank

1
2
3
4
5
6
7
8
9
class Shapes
{
...
}
class Rect : public Shapes
{
...
}
Make a vector of pointers to the base class. You can then assign the pointer to point to any of the objects that inherent from that base class.
Polymorphism yayyyy.
maybe a vector of the pointers?
std::vector<Shape*> instances
As highwayman said, if you store pointers to the base class and use virtual functions then the correct function will be called for the pointed-to type.

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
#include <iostream>
#include <vector>

class Shape
{
    int x, y;
public:
    Shape(int x, int y) : x{x}, y{y} {}
    virtual void draw() const = 0;
    void print_position() const
    {
        std::cout << "Position: " << x << ", " << y << '\n';
    }
};

class Rect : public Shape
{
    int dx, dy;
public:
    Rect(int x, int y, int dx, int dy) : Shape{x, y}, dx{dx}, dy{dy} {}
    void draw() const override
    {
        std::cout << "Rectangle:\n  ";
        print_position();
        std::cout << "  Size: " << dx << ", " << dy << '\n';
    }
};

class Circle : public Shape
{
    int radius;
public:
    Circle(int x, int y, int r) : Shape{x, y}, radius{r} {}
    void draw() const override
    {
        std::cout << "Circle:\n  ";
        print_position();
        std::cout << "  Radius: " << radius << '\n';
    }
};

int main()
{
    std::vector<Shape*> shapes;
    
    shapes.push_back(new Rect(10, 20, 30, 40));
    shapes.push_back(new Circle(50, 60, 70));

    for (const auto& sh: shapes)
        sh->draw();
}

Last edited on
Wow thank you for your help.
Without your help I'll never figure it out.
Topic archived. No new replies allowed.