Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 350
E235 Avatar asked Mar 11 '13 09:03

E235


2 Answers

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); 
like image 93
LihO Avatar answered Sep 21 '22 03:09

LihO


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)  {} 
like image 35
uba Avatar answered Sep 20 '22 03:09

uba