DartNyan DartNyan - 1 year ago 93
C++ Question

How to store objects with different types in a vector

I have three classes that inherit from the class component.
In class Computer I want to store objects of these 3 classes in a vector.

class Component {
public:
double price;
virtual void show() {
std::cout << "Price: " << this->price << std::endl;
}
};

class CPU : public Component {
public:
double price;
CPU(double price){ this->price = price; }
void show() {
std::cout << "CPU Price: " << this->price << std::endl;
}
};

class RAM : public Component {
public:
double price;
RAM(double price){ this->price = price; }
void show() {
std::cout << "RAM Price: " << this->price << std::endl;
}
};

class SSD : public Component {
public:
double price;
SSD(double price){ this->price = price; }
virtual void show() {
std::cout << "RAM Price: " << this->price << std::endl;
}
};

class Computer : public Component {
public:
std::vector<Component*> vec;
void show() {
for (auto el: vec) {
std::cout << el->price << std::endl;
}
}
};


But when I try to do it I see the garbage there:

Computer c;
c.vec.push_back((Component*)new RAM(10));
c.show(); // garbage
std::cout << c.vec[0]->price << std::endl; // garbage


I read a few questions about this on the stackoverflow, but still don't understand what I'm doing wrong.

qxz qxz
Answer Source

The problem is that you're declaring a double price; in each subclass. This creates separate fields, i.e. RAM::price and SSD::price, in addition to Component::price. Thus, when you construct a new RAM(10), it only assigns 10 to RAM::price, and not Component::price. That's why you're getting garbage.

To fix, simply remove all those extra declarations.

Also, to aid with properly deleting those pointers you've created, I'd highly suggest using a vector of smart pointers (probably std::vector<std::unique_ptr<Component>>). Then you could just:

c.vec.push_back(std::make_unique<Component>(new RAM(10)));

and use it as normal; the pointers will get deleted when the vector is destructed.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download