I have this class:
class CContact { public: CTimeStamp m_Stamp; int m_Num1; int m_Num2; CContact(CTimeStamp mStamp, int i, int i1) { m_Stamp = mStamp; m_Num1 = i; m_Num2 = i1; } };
I get the following error:
Constructor for ‘CContact’ must explicitly initialize the member ‘m_Stamp’ which does not have a default constructor
I want to be able to use it this way:
test.addContact(CContact(CTimeStamp(1, 2, 3, 4, 5, 6), 999999999, 777777777));
What does it mean, and how can I fix it?
Answer
The error is self-explantory. Your CContact
constructor is not passing any values to m_Stamp
‘s constructor, so the compiler has to default-construct m_Stamp
, but it can’t because CTimeStamp
does not have a default constructor.
You need to initialize CContact
‘s members (or at least m_Stamp
) in the CContact
constructor’s member initialization list rather than in the constructor’s body, eg:
CContact(CTimeStamp mStamp, int i, int i1) : m_Stamp(mStamp), m_Num1(i), m_Num2(i1) { }
This will invoke the copy constructor for m_Stamp
rather than the default constructor.
You original code was effective equivalent to this, which is why it failed:
CContact(CTimeStamp mStamp, int i, int i1) : m_Stamp() // <-- here { m_Stamp = mStamp; m_Num1 = i; m_Num2 = i1; }