I recently discovered the new - new to me anyway! - feature of modern C++ that allows you to set the initial value of a data member when you declare it:
1 2 3 4
|
class CINTWrapper{
private:
int m_iData=0;
};
| |
This even extends to calling member functions that help with initialization I believe:
1 2 3 4 5 6
|
class CStringWrapper{
private:
wchar_t* Allocate_Array(const int iBufferSize);
wchar_t* m_pString=Allocate_Array(1);
};
| |
At first, this seemed an extremely useful piece of functionality that C++ had been lacking all along. However, the more I thought about it the more it struck me this feature actually undermines one of the principle design elements of the language - that being the Constructor.
As I understand it the primary purpose of the Constructor is specifically to give the programmer a place where it is guaranteed he can always initialize his data members before anything else is done with the class. However, given the new initialization rules this is no longer necessary. So it largely seems to me that Constructors as a whole are no longer necessary either! I do appreciate Copy-Constructors are a special and vital case. Admittedly when I was using them for their intended purpose I hated either the redundancy you had to introduce across multiple Constructors; those with and without arguments and so on, or alternately the fine tuning of helper-functions to do common initialization between these variants. Now however I sort of regret this cast-iron rule has been taken away.
As a last point, I am trying to change the way I think about programming. I am trying to employ more objects than pure C-style ('int' or 'double', etc) data types and especially to move into templates (although absolutely NOT the Hewlett Packard template library!). Given my current understanding of inheritance in particular it seems to me that using pre-initialized data members rather than Constructor-initialization makes object derivation even more complicated, not less so.
What do you chaps think? Do you still use Constructors to initialize your data members or have you shifted over to the new style of working? If so, do you find it easier? Does it make the 'thinking ahead' that is required for working with inheritance and polymorphism more tricky for you?