Reputation: 1356
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
Reputation: 38969
There are 2 reasons why a constructor intializer list is the best choice where possible:
const
members, reference members, and member objects without default constructors can only be initialized in a constructor intializer listYes. 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
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