N
N
Nicky232020-10-05 05:24:36
C++ / C#
Nicky23, 2020-10-05 05:24:36

How to create a list from different class objects?

There are several classes:

class Figure { } // 1 Базовый
class Dot : public Figure { }
class Square : public Figure { }
class Circle : public Figure { }
class Decoration { } // Ещё один базовый
class Color : public Decoration { }
class Style : public Decoration { }
// И производный от них класс
class Ball : public Circle, public Color { }

We need to make a few more derived classes and add all this to the list.
My solution is this:
list<Figure*> figure_list;
Ball* ball = new Ball();
// Тут для ball доступно всё что нужно
Figure* figure = ball; // Теперь я вроде как могу добавить этот объект в список
// Но если обращаться к методам figure, то будет не хватать несколько

Since the figure contains a pointer to the Ball object, how to access it? And is it possible at all?
It's just that if there are a lot of objects in the list, then you won't be able to access the previously created ones.
And did I start right? Thanks in advance)

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Anton Zhilin, 2020-10-11
@Nicky23

First, the list (list) from Python is not std::list, but std::vectorin C ++.
Secondly, to get rid of problems with deleting objects, use std::unique_ptrfrom instead of regular pointers #include <memory>.
Object management will look something like this:

std::vector<std::unique_ptr<Figure>> figures;
std::vector<std::unique_ptr<Decoration>> decorations;

figures.push_back(std::make_unique<Ball>(аргументы для конструктора Ball));
figures[0]->какой-нибудь метод Figure

Thirdly, so that inheritance does not cause undefined behavior, you (in ordinary life, if you are not a compiler developer guru) must declare a virtual destructor in the base class: + for Decoration. Fourth, in essence, in order to be able to do something useful with Figure/Decoration, you need to add C ++ virtual functions (methods) to them and call them approximately as I wrote above. I suggest you explore this topic yourself. virtual ~Figure() = default;

A
Alexander Ananiev, 2020-10-05
@SaNNy32

https://docs.microsoft.com/en-us/cpp/cpp/dynamic-c...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question