Click to See Complete Forum and Search --> : Defined vs. Undefined Objects


ReoSoft
April 14th, 2004, 11:46 AM
I am new to the C++ language. I have been a VB programmer for the last 6 years. My question is about checking to see if an object has been instantiated.

In the world of VB, it is possible to see if an object has been instantiated with:
Dim myDatabase as Database

If myDatabase Is Nothing
//The database object is not present...don't need to do anything
Else
// The database object is instantiated...perform action like opening
End If
Does C++ .NET have something available to check to see if an object variable has been instantiated? Or do I have to set flags to maintain the state of objects?

Thanks,
Reo

Paul McKenzie
April 14th, 2004, 12:27 PM
In C++, there is no such thing as an "uncreated" object. You either have an instance of an object, or you don't.

There is no case where you can create an object, and the object is invalid. All created objects are valid in terms of C++, the question then comes is the object in a usable state for the task at hand.

There is this way to determine if a constructed object is usable,

1) Set a boolean flag within the object in the constructor. If the object is usable after construction, the flag is true, if not, the flag is set to false.

class foo
{
public:
foo() : bIsValid(false)
{
/* code to initialize foo */
if ( /* initialization OK */ )
bIsValid = true;
}

bool IsValid( ) const { return bIsValid; }

private:
bool bIsValid;
};

Then the client, after creating the object, calls foo::IsValid( ) to determine if the object is usable.

Another way is to throw an exception error in the constructor. Then the client program is responsible for catching the thrown exception. In this case, no object was created, while in the first case, an object was created.

Regards,

Paul McKenzie