Assume I have a C++ class like this:
class Container
{
private:
union {
Foo* foo;
Bar* bar;
} mPtr;
};
This class will be constructed on the stack. I.e. it won't be newed, so I can't just declare a zeroing operator new.
Can I use the initializer in the constructor to set mPtr to nullptr somehow?
Container()
: mPtr(nullptr)
{
}
does not compile. Not even by adding a dummy union member of type nullptr_t.
Container()
: mPtr.foo(nullptr)
{
}
doesn't compile, either.
Use aggregate initialization, for example:
Container() : mPtr { nullptr }
{ }
I don't normally like posting links, but here is a good run through of this technique.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With