Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compiler error because constructor must explicitly initialize the member

I have class CFirst and CSecond. I can't do anything with the second class, but I can do something with the first one.
I am trying to create an object from the second one in the first one, but the compiler is still not satisfied.

The best so far is this:

class CFirst{
    public:
    CSecond m_sec;
    CFirst ( const CSecond & sec ) {
          CSecond m_sec(sec.a(),sec.b());
     };

class CSecond{
    public:
    CSecond ( int a, int b) : m_A ( a ), m_B ( b ){ }
    int a  ( void ) const { return m_A;  }
    int b ( void ) const { return m_B; }
    private:
    int m_A;
    int m_B;
};

but complier says:

constructor for 'CFirst' must explicitly initialize the member 'm_sec' which does not have a default constructor.

Do you have some advice?

EDIT:

I did also try (no success)

 m_sec(sec.a(),sec.b());

instead of

 CSecond m_sec(sec.a(),sec.b());

The explanation is in comments below answer.

like image 270
Smeagol Avatar asked Dec 18 '22 08:12

Smeagol


1 Answers

Inside the constructor of CFirst, CSecond m_sec(sec.a(),sec.b()); doesn't initialize the member m_sec, but defines a local object with name m_sec, which has nothing to do with the member m_sec. (And it hides the member m_sec.)

You should use member intializer list instead, e.g.

CFirst ( const CSecond & sec ) : m_sec(sec.a(), sec.b()) {} // initialize data member m_sec via CSecond::CSecond(int, int) 

or

CFirst ( const CSecond & sec ) : m_sec(sec) {} // initialize data member m_sec via CSecond's copy constructor 

Additional explanations

Non-static data members can only be initialized by member intializer list or default intializer list (since C++11). You just can't do it inside the constructor's body. So CSecond m_sec(sec.a(),sec.b()); will define a new local variable, and m_sec = sec; is an assignment; before the assignment m_sec will be tempted to be default intialized. But CSecond doesn't have default constructor, which cause the compile error.

like image 141
songyuanyao Avatar answered Dec 20 '22 21:12

songyuanyao