Mattia Paterna Mattia Paterna - 1 month ago 14
C++ Question

defining a class constructor

I'm dealing with my very first course on programming in C++ and that's the way in which I've been told to define a class constructor:

class_name(int x, int y){
this->x=x;
this->y=y;
};


If I understood correctly, as I've found several times here, I could rewrite it this way:

field(int x, int y) : m_x(x), m_y(y){};


having however this protected variables:

protected:
int m_x, m_y;


instead of

protected:
int x, y;


Are there any differences between them or is it just different ways of writing?

And, if so, why the need of having different m_x and x variables?

I hope this is not such a silly questions, but I'd like to really understand it.

peace.

Answer

Q1. Should I use a constructor initializer list or initialize in the body of the constructor?

There are 2 reasons why a constructor intializer list is the best choice where possible:

  1. const members, reference members, and member objects without default constructors can only be initialized in a constructor intializer list
  2. Member objects which are initialized in the body of the constructor must be default constructed and then initialized separately; which misses out on optimization opportunities and prevents those objects from having any of the members called out in 1

Q2. Should I use a naming convention for member variables?

Yes. Google, for example, recommends naming member variables with a trailing underscore, but an m_ prefix accomplishes the same goal of saving the reader the time of looking up whether this variable was declared in the current scope, or whether this variable is a member variable.