-1

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?

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
Etoail
  • 1
  • 1
  • Related: [https://stackoverflow.com/questions/926752/why-should-i-prefer-to-use-member-initialization-lists](https://stackoverflow.com/questions/926752/why-should-i-prefer-to-use-member-initialization-lists) – drescherjm Mar 14 '21 at 20:20
  • https://stackoverflow.com/q/1711990/212858 isn't a duplicate, but it _does_ answer your question – Useless Mar 14 '21 at 20:20

2 Answers2

0

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;
}
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
0

You have to define a default constructor for class CTimeStamp. For example:

CTimeStamp(int aa=0, int bb=0, int cc=0)
:a{aa},b{bb},c{cc}{}
jiadong
  • 135
  • 7