Re: return value
Note up front: this has nothing to do with the MFC, dropping mpvm from the
list of groups.
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?
Doug already pointed out the differences to the Java object model, and that
the closest in C++ is a pointer.
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;
}
No:
1. In what way is 'FieldName' modified? If it isn't, make it 'const',
because otherwise the function implies that it is. Other than that, in C++
you should use a string class like std::string or CString.
2. Use initialisation instead of assignment, i.e. merge the two first line
of this function. Further, it helps actually making such values constant,
so you don't accidentally modify them later on.
3. I'm pretty sure that it doesn't compile, so it obviously isn't
correct. ;)
Doug mentioned some ways to solve this, but I'd like to add two of them:
1. If you can't return something from a function, just like in Java, you can
throw an exception. I would for example use std::runtime_error from
<stdexcept> which allows carrying a std::string as additional info. In some
cases it would even make sense to derive an own exception type. This avoids
having to check each and every returnvalue when the only thing you can do
is to forward the error.
2. If you need to pass an object to the caller, and the caller is supposed
to assume ownership of it, use std::auto_ptr. Its semantics are a bit
confusing at first, but they come very handy in practice.
Uli
--
C++ FAQ: http://parashift.com/c++-faq-lite
Sator Laser GmbH
Gesch??ftsf??hrer: Michael W??hrmann, Amtsgericht Hamburg HR B62 932