Answer the question
In order to leave comments, you need to log in
How to correctly allocate memory for an array of C++ classes?
I'm feeding a library for Android.
There is such a class
class ButtonProcessor{
private:
Button buttons[];
public:
ButtonProcessor(Button buttons[]);
void run();
};
Answer the question
In order to leave comments, you need to log in
@Deerenaros correctly wrote that it's not entirely clear what you want,
but at the same time a piece of code
Button *buttons = new Button[100500];
Button Processor proc(buttons);
together with the constructor according to modern concepts contains several errors.
It’s better not to do this, you will have to remember that you need to call delete[], while it is desirable to call delete[] after the ButtonProcessor destructor has completed (the destructor can use buttons), but this is impossible in the above code.
Heap initialization of a variable in the body of a constructor is also a bad approach, read c++ RAII en.wikibooks.org/wiki/More_C%2B%2B_Idioms/Resource...
Yes, and C++ constructors have a syntax for initializing name(params) : button(button) which allows you to avoid a number of problems, see pr RAII
What to do? As an option, stop using arrays in their pure form and use std::vector from the standard library,
or install boost - read about boost containers, about smart pointers, and use either ready-made containers such as boost::array or boost::shared_array,
Then memory problems, etc. you will avoid, so instead of writing code - devote time - and read useful literature I
recommend starting with C ++ faq
www.parashift.com/c++-faq
then run here
en.wikibooks.org/wiki/More_C%2B%2B_Idioms
and read about boost - boost.org
After reading the above, you will not have any questions about what, where, how and where.
Without all this, C++ code will turn into a continuous popbole for you.
Oh wei. C++ can manage memory in much more sophisticated ways than Java or C#, so learn stack and heap , read about pointers and dynamic memory allocation .
Your question is worded incorrectly. It's not entirely clear what you want to do. If you need to store a previously created array of buttons, then pass a pointer, and before that, create it with the new operator:
class ButtonProcessor{
private:
Button *buttons;
public:
ButtonProcessor(Button *buttons) {
this->buttons = buttons;
}
};
/***/
Button *buttons = new Button[100500];
ButtonProcessor proc(buttons);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question