I'm creating a program which has an abstract base class called component, I have 3 classes inductor, resistor and capacitor which inherit from components. I have a vector:
std::vector<component*> components;
Which is a member of a class called circuit. So components contains pointers to component objects (whether that be resistor, capacitor or inductor).
Now my problem arises when I try and create a new vector, initialized as so:
std::vector<component*> temp_components = components;
Currently the vector only contains resistor objects, so I have a copy constructor in 'resistor.cpp':
resistor::resistor(const resistor& resistor)
{
impedance = resistor.impedance;
voltage_frequency = resistor.voltage_frequency;
name = resistor.name;
resistance = resistor.resistance;
}
And also an assignment operator in resistor:
resistor& resistor::operator=(resistor& rhs)
{
//Check if equal
if (&rhs == this) {
return *this;
}
delete& impedance; delete& voltage_frequency; delete& name; delete& resistance;
impedance = rhs.impedance;
voltage_frequency = rhs.voltage_frequency;
name = rhs.name;
resistance = rhs.resistance;
return *this;
}
However, when I run the code to create temp_components equal to components, the pointers in the 2 vectors are the same, so when I change a value in temp_components, it does the same in components, which is not what I want.
I think this is because of the way vector works for pointers, but I have no idea where to begin in fixing this problem. I want to make it so the details (class members) of the components which the pointers point to are copied, but the pointers don't both point to the same memory location.