Reputation: 1887
I have a class, let's call it Polynomials.
The number of needed Polynomials are not known in advance and are determined at run-time. My current implementation uses a container class, let's call it Solutions, in which there is a vector, let's call it polynomialVector, it is defined this way:
std::vector<Polynomial> polynomialVector;
The vector is created and populated in this way (The constructor of Solutions do this job):
polynomialVector.reserve(numberofneededpolynomials);
for(int i = 0; i < numberofneededpolynomials ; i++) {
polynomialVector.emplace_back(0) //Polynomial constructor takes an int parameter
}
Now I want to create specific type of polynomials that will inherit from the general polynomials class. The type of polynomial will be determined at run time by the user. For example if the user inputs 0, then the general Polynomial class is used, if he inputs 1, then a specific derived polynomial class is used, for type 2, a different specific type of polynomial is used, etc.
I've seen in examples that this can be done using regular arrays:
Polynomial * polynomial1 = new DerivedPolynomial1(parameters);
Polynomial * polynomial2 = new DerivedPolynomial2(parameters);
Polynomial * arrayPolynomial[2] = {polynomial1, polynomial2};
But I need to do it using vectors since the application creates a number of different polynomials (created randomly by the polynomial class but this is not relevant) that is not known in advance. And my entire code that wraps the Polynomial class (the Solutions class) is already coded for vectors.
I need to do something like this:
cin >> type;
if(type == 0) {
polynomialVector.reserve(numberofneededpolynomials);
for(int i = 0; i < numberofneededpolynomials ; i++) {
*create polynomial of type 0 in a similar way that emplace_back does for the general case that I described*
}
if(type == 1) {
... same thing but for type 1
}
How to do this?
Upvotes: 0
Views: 1654
Reputation: 977
To store a polymorphic datatype in a std::vector, you need to store pointers.
To make sure the code doesn't leak memory, the easiest is to use a smart pointer.
std::vector<std::unique_ptr<Polynomial>> polynomialVector;
polynomialVector.emplace_back(new DerivedPolynomial1(parameters));
I assume you use C++11, since your code uses emplace_back
Upvotes: 4
Reputation: 56549
You should store them as pointers, something like below:
std::vector<Polynomial *> polynomialVector;
^
Also, you must handle memory (new/delete) and push derived objects as pointer to the vector.
Feel free to use std::unique_ptr
or std::shared_ptr
instead of simple pointers:
std::vector<std::unique_ptr<Polynomial>> polynomialVector;
or
std::vector<std::shared_ptr<Polynomial>> polynomialVector;
Upvotes: 0