Search code examples
c++initialization-list

Is it required to define the initialization list in a header file?


Recently I created class Square:

=========header file======

class Square
{
    int m_row;
    int m_col;

public:
    Square(int row, int col): m_row(row), m_col(col) 
};

==========cpp file======

#include "Square.h"

Square::Square(int row, int col)
{
    cout << "TEST";
}

but then I receive lots of errors. If I remove the cpp file and change the header file to:

=========header file======

class Square
{
    int m_row;
    int m_col;

public:
    Square(int row, int col): m_row(row), m_col(col) {};
};

it complies with no errors. Does it mean that initialization list must appear in the header file?


Solution

  • You can have

    ==============header file ================

    class Square
    {
        int m_row;
        int m_col;
    
    public:
        Square(int row, int col);
    };
    

    ==================cpp ====================

    Square::Square(int row, int col):m_row(row), m_col(col) 
    {}