Search code examples
c++c++11referencevariable-initialization

Why reference with operator = works but with constructor don't?


As far as I know the following statements are the same:

A a1(1);
A a2=1;

Header:

class A
{
   public:
      A(int num){}
};

But when using reference it won't compile

class B{
   private:
      int m_a = 0;
      int& m_b(m_a);

   public:
      B(int num):
      {
      }
};

got compile error stating m_a is not a type name but when doing this with = it works:

class B
{
   private:
      int m_a = 0;
      int& m_b = m_a;

   public:
      B(int num):
      {
      }
};

Solution

  • In-class member initialization is different from other forms of initialization.

    The only supported syntax for in-class member initialization are:

    int& m_b = m_a;
    int& m_b{m_a};
    

    You can read more about it at https://en.cppreference.com/w/cpp/language/data_members#Member_initialization.