Re: return value
Carmen Sei wrote:
Is there any way to return either NULL or a SYSTEMTIME object? will
it work in C++?
as in Java, one can return either NULL or an object, does C++ has
something similar?
Is the following code OK for C++?
=================
SYSTEMTIME Table::Get(char* FieldName)
{
_variant_t vtValue;
vtValue = m_Rec->Fields->GetItem(FieldName)->GetValue();=
if (vtValue.vt == VT_NULL) {
return NULL;
}
SYSTEMTIME m_st;
VariantTimeToSystemTimeWithMilliseconds (vtValue.date, &m_=
st);
return m_st;
}
Have you tried to compile it?
C++ distinguishes between objects and pointers to objects (in contrast
to Java, where everything is a pointer to an object). Thus you can
specify in C++ that a function will always return a valid object
(something that cannot be NULL, so you don't have to write code to
check that the return value is actually non-NULL) by making the return
type an object:
SYSTEMTIME Table::Get(char* FieldName)
This will always return a valid SYSTEMTIME (unless it throws an
exception).
The semantics you want to express is a bit different. What you
actually want to specify is a method that returns a valid SYSTEMTIME
when a certain condition is met, or a value that indicates that no
meaningful SYSTEMTIME could be returned because the condition is _not_
met (in your case the condition is that the data base contains an
entry that can be coerced into a SYSTEMTIME in the specified field).
You have two alternatives to design this:
(A) Use a special DATETIME value that indicates that you could not
retrieve such a value from the data base (for example you could use
the time where all members are set to zero).
(B) Return a pointer to a DATETIME, which will be NULL if the
condition isn't met. In this case the called method will have to
allocate memory on the heap, so the calling entity would have to
ensure that this memory is properly released. The standard way of
doing this is making the return type an auto_ptr:
std::autoptr<SYSTEMTIME> Table::Get(char* FieldName);
The auto_ptr will ensure that the memory is properly released, and
above all this is the exception-safe way of returning new'ed objects
(see Herb Sutter's "Exceptional C++" for a better description).
Both alternatives are equally well suited to do what you want,
alternative B is a bit closer to the way a Java programmer would
handle such a case.
Regards,
Stuart