I'm a bit stumped about how you would achieve something like that in C++. I have the feeling it might have to do with my architecture.
Let's say I have a a garage in Montreal and in this garage, there are different cars.I would usually go with a vector of pointers to base class Car here. Here is the problem though, I then want to deep copy the garage and open one in Miami. Futhermore, the Saab cars needs to have a different copy constructor, but with the same signature. There will be other exceptions like this down the road. I don't know what's in the Garage beforehand. Here is the code I have so far.
//base class
class Car
{
public:
Car(int speed);
private:
int speed;
}
class Garage
{
public:
Garage(){};
//copy constructor of the garage
Garage(const Garage &toCopy)
{
for(int i=0;i<toCopy.cars.size();i++)
{
ReceiveCar(*cars[i]);
}
}
vector<std::shared<Car>> cars;
template <typename T>
T* ReceiveCar()
{
std::shared_ptr<T> ptr = std::make_shared<T>();
cars.push_back(ptr);
return ptr.get();
}
T* ReceiveCar(Car &toCopy)
{
std::shared_ptr<T> ptr = std::make_shared<T>(toCopy) cars.push_back(ptr);
return ptr.get();
}
}
class Saab : public Car
{
public:
Saab(int speed)
:Car(speed)
{
DoWork();
};
}
class AstonMartin: public Car
{
public:
AstonMartin(int speed)
:Car(speed)
{
DoImportantStuff();
};
AstonMartin(const AstonMartin& toCopy)
:Car(toCopy.speed)
{
DoImportantStuff();
};
}
Of course, the copy constructor used is the implicit one from Car. Is it possible to call the derived class' one instead without dynamic casting between ifs/elses for every exception to the rule there is. Maybe store each derived classes with the pointer somehow?
PS:I know I should not be returning raw pointers, but the destructors for the cars are private in my code, so the shared_pointers are still safe.