Constructor parameters with the same name as data members

  • Thread starter dwightarmyofchampions
  • Start date
D

dwightarmyofchampions

Can I have my constructor parameters be the same name and type as my
data members? If so, do I have to use the member initialization list?
What if one of them is a vector that requires a for loop?
 
R

red floyd

Can I have my constructor parameters be the same name and type as my
data members? If so, do I have to use the member initialization list?
What if one of them is a vector that requires a for loop?

Yes you can. I don't believe it's a good idea because it can lead to
confusion,
and maintainability issues.

What you want to do will work in an initialization list, I don't
believe it will work inside
the constructor body.


Is it so hard to add a trailing _ to either your constructor
parameters or to your member variables?

e.g.:

class A {
int x;
int y;
public:
A(int x_, int y_) : x(x_), y(y_) { }
};
 
J

James Kanze

On Mar 19, 9:35 am, (e-mail address removed) wrote:
Yes you can. I don't believe it's a good idea because it can
lead to confusion, and maintainability issues.

In general, I agree. But for very simple "classes", with all
data members public, I'll sometimes make an exception.
What you want to do will work in an initialization list, I
don't believe it will work inside the constructor body.

Inside the constructor body, the name refers to the parameter
(which hides the member); you can always access the member using
this->, however.
Is it so hard to add a trailing _ to either your constructor
parameters or to your member variables?

It is if you have any esthetic sensibility:).

Generally speaking, the case should rarely occur. Variable
names are qualified nouns; the parameters will have names
like newSomething or initialSomething, whereas the members will
have names like mySomething (or ourSomething, in the case of
static members).
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,578
Members
45,052
Latest member
LucyCarper

Latest Threads

Top