Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to name constructor parameters when using non-prefixed member variables?

Certainly there is no one right way to do this, but I can't even think of any decent naming scheme, that's why I'm asking here. (So: While all answers will be subjective, they will be useful nevertheless!)

The problem is as follows: For simple aggregate structs, we do not use member var prefixes.

struct Info {
  int x;
  string s;
  size_t z;

  Info()
  : x(-1)
  , s()
  , z(0)
  { }
};

It is nevertheless sometimes useful to provide an initializer ctor to initialize the struct, however - I cannot come up with a decent naming scheme for the parameters when the most natural names for them are already taken up by the member variables themselves:

struct Info {
  int x;
  string s;
  size_t z;

  Info(int x?, string s?, size_t z?)
  : x(x?)
  , s(s?)
  , z(z?)
  { }
};

What are other people using in this situation?

like image 703
Martin Ba Avatar asked Mar 09 '11 13:03

Martin Ba


People also ask

How do you name a constructor parameter?

Parameter NamesThe name of a parameter must be unique in its scope. It cannot be the same as the name of another parameter for the same method or constructor, and it cannot be the name of a local variable within the method or constructor. A parameter can have the same name as one of the class's fields.

Do you have to initialize all variables in constructor?

in short.. it's fine to not initialize your member variables in the constructor as long as you initialize them somewhere in the class before using them.. Save this answer.

Are member variables initialized before constructor C++?

Const member variables must be initialized. A member initialization list can also be used to initialize members that are classes. When variable b is constructed, the B(int) constructor is called with value 5. Before the body of the constructor executes, m_a is initialized, calling the A(int) constructor with value 4.

What does every variable need to be prefixed with?

The value of a Variable can be accessed using the symbol prefix ##. Both Local and Global Variables can be retrieved using ##.


2 Answers

Use the same names - they don't collide.

"During the lookup for a name used ... in the expression of a mem-initializer for a constructor (12.6.2), the function parameter names are visible and hide the names of entities declared in the block, class or namespace scopes containing the function declaration." 3.4.1 C++ 2003

like image 135
fizzer Avatar answered Nov 06 '22 23:11

fizzer


Why invent pre/postfixes? I just use the same name. C++ is designed for that to work.

struct Info {
  int x;
  string s;
  size_t z;

  Info(int x, string s, size_t z)
  : x(x)
  , s(s)
  , z(z)
  { }
};

It's straight forward.

like image 33
Johannes Schaub - litb Avatar answered Nov 06 '22 23:11

Johannes Schaub - litb