In article <>,
wrote:
> Hello,
>
> I have a question about passing an object into a constructor.
>
> How can I check to make sure that the object is good/valid that is
> being passed into the constructor.
>
> Obviously I could check to see if it is non-NULL, but that still will
> not necessarily tell me anything.
>
> For example:
>
> /* here is a constructor car that takes an engine class as an
> argument. But, I better check to make sure that engine is valid
> so how do I do that?
> */
> Car::Car( Engine* engine )
> {
>
> // check to make sure that engine is valid.
>
>
> }
In other words, you want to guard against someone doing something like:
Car myCar( (Engine*) 0x543562 );
(where 0x543562 doesn't point to an actual Engine object.) Or some such?
There isn't much you can do about this, but here is one idea:
class Engine {
static std::set< Engine* > allEngines;
public:
static bool isValid( Engine* anEngine ) {
return allEngines.count( anEngine ) == 1;
}
Engine() {
allEngines.insert( this );
}
~Engine() {
allEngines.erase( this );
}
};
Now:
Car::Car( Engine* engine ) {
assert( Engine::isValid( engine ) );
//...
}
This is not a cheep operation! It will probably slow your program down
tremondusly if you do this with every class. Be sure to make it so you
can define the extra code out when you build a release version.