Seems like this would be a duplicate, but maybe it is just so obvious it hasn't been asked...
Is this the proper way of checking if a variable (not pointer) is initialized in a C++ class?
class MyClass
{
void SomeMethod();
char mCharacter;
double mDecimal;
};
void MyClass::SomeMethod()
{
if ( mCharacter )
{
// do something with mCharacter.
}
if ( ! mDecimal )
{
// define mDecimal.
}
}
With C++-11 you could consider storing the variable using smart pointers. Consider this MVE where
toString()
behaviour depends onbar
being initialized or not:Using this code
produces the output
There is no way of checking of the contents of a variable are undefined or not. The best thing you can do is to assign a signal/sentinel value (for example in the constructor) to indicate that further initialization will need to be carried out.
If for instance you use strings instead of chars, you might be able do something like this:
You could reference the variable in an assertion and then build with
-fsanitize=address
:This will cause the program to reliably crash with a stack trace (as opposed to undefined behavior).
There is no way in the C++ language to check whether a variable is initialized or not (although class types with constructors will be initialized automatically).
Instead, what you need to do is provide constructor(s) that initialize your class to a valid state. Static code checkers (and possibly some compilers) can help you find missing variables in constructors. This way you don't have to worry about being in a bogus state and the
if
checks in your method can go away completely.With C++17 you can use
std::optional
to check if a variable is initialized:This will produce the output:
To use
std::optional
in the code snipped you provided, you'll have to include the<optional>
standard library header and addstd::optional<...>
to the respective variable declarations: