Is it required to define the initialization list in a header file?
C++Initialization ListC++ Problem Overview
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?
C++ Solutions
Solution 1 - C++
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);
Solution 2 - C++
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)
{}
Solution 3 - C++
The initialization list appears with the constructor definition, not with a declaration that isn't a definition. So, your options are either:
Square(int row, int col): m_row(row), m_col(col) {}; // ctor definition
in the class definition or else:
Square(int row, int col); // ctor declaration
in the class definition and:
Square::Square(int row, int col): m_row(row), m_col(col) {} // ctor definition
elsewhere. "Elsewhere" is allowed to be in the header, if you make it inline
.
Solution 4 - C++
Not a requirement. It can be implemented in a source file as well.
// In a source file
Square::Square(int row, int col): m_row(row),
m_col(col)
{}
Solution 5 - C++
This kind of initializing a variable called member initialization list. Member initialization list can be used in header file or source file. That doesn't matter. But the constructor must have definition when you initialize it in header file. You can refer https://stackoverflow.com/questions/7665021/c-member-initialization-list for more details.