Mattia Paterna
Mattia Paterna

Reputation: 1356

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.

Upvotes: 1

Views: 94

Answers (2)

Jonathan Mee
Jonathan Mee

Reputation: 38969

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.

Upvotes: 1

Raindrop7
Raindrop7

Reputation: 3911

the first type of initializing x and y is inside a the constructor body and the second you used member initializer-list.

they are the same but there are where you must use member-list initializer when using inheritance so you can't call the base constructor inside the body of derived class's constructor definition. eg:

class A
{
    public:
        A(int x) : _x(x){} // ok
//      A(int x) {_x = x;} ok
    protected:
        int _x;
};

class B : public A
{
    public:
    //  B(int x) {A(x);} error here
        B(int x) : A(x){} // we must use member initializer list here
};

Upvotes: 1

Related Questions