Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: Initialization Lists / Naming conventions

The following code works on my machine, but is it good practice / guaranteed to work?

struct MyStruct {
   MyStruct(int x, int y, int z) :
       x(x),
       y(y),
       z(z) {
   }

   int x;
   int y;
   int z;
};

Specifically, is x(x) guaranteed to do what I want? (that is, does the variable in an initialization list always look at that struct/class' member?)

I don't want to use leading or trailing underscores since x is a public member of the struct.

Thanks!

like image 492
FrankMN Avatar asked Jan 30 '11 18:01

FrankMN


People also ask

What is initialization list in C?

An initialization list is used to initialize a data member of reference type. Reference types can only be initialized once. 20. 1. #include<iostream>

Is CPP a CamelCase?

C++ code. Use CamelCase for all names. Start types (such as classes, structs, and typedefs) with a capital letter, other names (functions, variables) with a lowercase letter.

Is initialization list faster?

Conclusion: All other things being equal, your code will run faster if you use initialization lists rather than assignment. Note: There is no performance difference if the type of x_ is some built-in/intrinsic type, such as int or char* or float .

How do I name a CPP file?

For C++ files, prefer naming the file the same as the (main) class it contains. Currently all file names are all-lowercase, even though class names contain capital letters.


2 Answers

Yes, that is guaranteed to do what you expect.

The only thing that can exist "outside" the parentheses in an initializer list are member variables. And inside the parentheses, the usual rules apply; local variables hide member variables.

As to whether it's good practice, well, consider what happens if you accidentally remove one or more of the arguments from the constructor argument list. The code will still compile fine! But it will break horribly at runtime. Nevertheless, I still use this pattern fairly frequently.

like image 155
Oliver Charlesworth Avatar answered Sep 18 '22 17:09

Oliver Charlesworth


While it expects what you do, imagine this situation by extension:

class MyStruct {
public:
   MyStruct(int x, int y, int z)
   :   x(x),
       y(y),
       z(z) 
   {   }
   int x() const;
   int y() const;
   int z() const;

private:
   int x;
   int y;
   int z;
};

Which will not work. That's why I prefix my class members with m_. This allows very readable code with a hint to the reader that the identifier in question is part of the class. Non-prefixed identifiers are either function arguments (like in the constructor initializer list: m_x(x), or function local variables).

like image 43
rubenvb Avatar answered Sep 18 '22 17:09

rubenvb