

Holding Model Class Objects in Array
source link: https://www.codesd.com/item/holding-model-class-objects-in-array.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Holding Model Class Objects in Array
I have to hold different type of datas in one array for my project. I've created a template class for generating objects.
template<class Queue>
class Template {
public:
Queue value;
Template(Queue input) {
value = input;
}
};
But I can't hold them in one array without using abstract class. I've created a void pointer array for this. And I used it liked that;
void *array[21];
array[index] = new Template<int>(number);
array[index] = new Template<string>(text);
Is there any possible solution without abstract classes? I mean, can i hold this template objects in template class' array?
Create a hierarchy and take advantage of dynamic binding:
class Base {
public:
virtual ~Base() {};
// ...
};
template<class Queue>
class Template : public Base {
Queue value;
public:
Template(Queue const &input) :value(input) {}
// ...
};
And use it as:
Base *array[21];
array[index] = new Template<int>(number);
array[index + 1] = new Template<string>(text);
Furthermore, instead of using raw array and raw pointers use STL facilities like std::array
smart pointers (e.g., std::shared_ptr<Base>
or std::unique_ptr<Base>
):
std::array<std::unique_ptr<Base>, 21> arr;
arr[index].reset(new Template<int>(number));
arr[index + 1].reset(new Template<string>(text));
Also prefer to initialize member variables to the constructor's initializer list than to its body.
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK