Reputation: 17
I have a file that contains a list of names, colors, and some statistics about them. For example:
John black 10 15
Adam black 19 18
Jake brown 13 51 56 62
Rich brown 13 09 98 84
I want to be able to store those names, colors, and numbers in their respective objects based on their colors. So John and Adam, would be stored in the class Black, Jake and Rich would be stored in class Brown.
How can I store each person in their respective objects since they are different types?
class Color{
public:
Color(string FIRST, string COLOR);
protected:
string FirstName;
string ColorType;
};
class Black : public Color{
public:
Black(string FIRST, string COLOR, int A, int B);
private:
string FirstName;
string ColorType;
int number1, number2;
};
class Brown : public Color{
public:
Brown(string FIRST, string COLOR, int A, int B, int C, int D);
private:
string FirstName;
string ColorType;
int number1, number2, number3, number4;
};
Upvotes: 0
Views: 1291
Reputation: 28178
Make a container of base class pointers:
std::vector<std::unique_ptr<Color>> colors;
and insert allocated derived classes:
colors.emplace_back(new Black("John", "Black", 10, 15));
Upvotes: 6
Reputation: 64308
Typically you would have a list of pointers to the base type, and create instances of the derived types. Refer to Dave's answer to see how to do it with C++11. For older versions of C++, you would typically make the Color destructor virtual and create a wrapper to manage memory, or perhaps use boost.
Upvotes: 0