I have a composition object that is written in C++. The container class deletes the dynamic object in its destructor. However, if someone creates the object in the main and passes it to the container class, they will probably try to delete the dynamic object in their code. How do I test to see if the object exists before I delete it? The code below crashes since the dynamic Engine was deleted in the main. However, I need to clean up the memory in the class in case the Vehicle is created with the default constructor and the main() never uses the "new" keyword. Thanks!
int main( ){
// create composition object
Engine * engine = new Engine( );
Vehicle vehicle( engine );
// clean the memory
delete engine;
}
class Vehicle{
public:
// constructors
Vehicle( ){
engine = new Engine( );
}
Vehicle( Engine * engine ){
this->engine = engine;
}
// destructor
~Vehicle( ){
delete engine;
}
private:
Engine * engine;
};