This is going to sound so basic as to make one think I made zero effort to find the answer myself, but I swear I did search for about 20 minutes and found no answer.
Value will be undefined.
You may have one "ultimate" ctor which will initialize all fields and add "short-cut" ctors with only part of parameters, which will pass these params to ultimate ctor along with default values for the rest of params.
You're thinking correctly. If you don't initialise it, it could be anything.
So the answer to your question is yet, either initialise it with something, or give it a NULL (or nullptr, in the most recent C++ standard).
class A
{
};
class B
{
private:
A* a_;
public:
B() : a_(NULL) { };
B(a* a) : a_(a) { };
};
Our default ctor here makes it NULL (replace with nullptr
if needed), the second constructor will initialise it with the value passed (which isn't guaranteed to be good either!).
The value will be uninitialised so yes you do need to explicitly initialise it to nullptr
.
Using smart pointers (std::unique_ptr
, std::shared_ptr
, boost::shared_ptr
, etc.) would mean that you don't need to do this explicitly.
the value of any uninitialized pointer is always garbage, it's some random memory address.
in your constructors, you can use initializer lists to initialize your pointer
simply
MyClass::MyClass() : myPointer(nullptr)
{
}
trying to reference an uninitialized pointer triggers undefined behavior. so ALWAYS initialize your pointer.