If you're using C++11, you can just initialize to nullptr in the class body's definition.
class Test
{
private:
Model *model = nullptr; //Initialized.
public:
Test() //: model(nullptr) <-- Not needed
{
model = new Model();
}
~Test()
{
delete model;
}
}
Also, you may want to also consider smart pointers. A std::unique_ptr is usually the same size as a regular pointer*, and deletes itself when the class gets deleted. Depending on your performance needs, a unique_ptr for situations like this may save some programmer mistakes.
Alternatively, 'model' might not need to be heap-allocated at all depending on what you are doing.
*if using the default deleter.
=================
As far as the initialization list goes, there's a gotcha you need to be careful about:
class Something;
class Test
{
public:
Test() : something(this) //Careful when passing the 'this' pointer in the initializer list.
{
something.DoSomething(); //Fine. 'something' is fully constructed.
}
void Blah()
{
//...
}
private:
Something something;
};
class Something
{
public:
Something(Test *test) : test(test) //Fine, we're just storing the pointer address.
{
test->Blah(); //ERROR! 'Test' hasn't been fully constructed yet!
}
void DoSomething()
{
test->Blah(); //Fine. 'test' is fully constructed.
}
private:
Test *test = nullptr;
};
If we initialize a member in an initialization list, and pass it a pointer to ourself, we haven't yet been fully constructed yet!
During the initialization list, our memory has already been allocated and the 'this' pointer points to the right space, but that memory hasn't been initialized yet, so that pointer can't be used to read or write to our members or call functions that read or write to the members. It'd be undefined behavior. It likely won't crash, because the pointer address points to legit memory, but the memory contents are still gibberish.
As far as using the 'this' pointer goes, we can store it, but we can't predictably use it until we reach the constructor's function-body (which is after the initializer list has already been gone over).