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

E235 picture E235 · Mar 11, 2013 · Viewed 33k times · Source

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?

Answer

LihO picture LihO · Mar 11, 2013

Initialization list is part of constructor's definition so you need to define it at the same place you define constructor's body. This means that you can have it either in your header file:

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

or in .cpp file:

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

but when you have definition in .cpp file, then in header file, there should be only its declaration:

public:
    Square(int row, int col);