DaKoadMunky said:
...
class Car
{
public:
Car(Engine& engine) //Can't be null
:m_engine(&engine)
{
}
void ReplaceEngine(Engine& engine) //Can't be null
{
m_engine = &engine;
}
private:
Engine* m_engine;
};
Depending on how an Engine is allocated it is possible that any run-time check
for failure will need to be dealt with elsewhere, but at the minimum Car should
not have to worry about whether or not it has an engine to forward commands to.
Just be careful. Overall, the design isn't any safer ...
What if an engine is create on the stack - and then passed into this
constructor ... and then the engine goes out of scope
Its all contextual of course, but it might be better to actually copy
the engine into the car and not try to maintain a pointer to an engine
created outside the Car.
--------------------------------
#include <iostream>
struct Engine
{
public:
void start () const
{
std::cout << "starting ..." << std::endl;
}
};
struct Car
{
public:
Car(Engine& eng)
: engine(&eng)
{
}
const Engine* get_engine () const
{
return engine;
}
private:
Engine* engine;
};
class Mechanic
{
public:
Car* create_car ()
{
// bad decision, but it compiles and might even run
Engine engine;
Car* car = new Car(engine);
return car;
}
};
int
main(int argc, char** argv)
{
Mechanic m;
Car* car = m.create_car ();
const Engine* engine = car->get_engine ();
// EEK --- where is the car's engine?
engine->start();
delete car;
return 0;
}
--------------------------------
In this toy program, the address still holds (VC++ 7.1) so the program
runs ... but its undefined behavior since the Engine has long since gone
out of scope.
Hth,
-Luther