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?
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);
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) {}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With