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!
An initialization list is used to initialize a data member of reference type. Reference types can only be initialized once. 20. 1. #include<iostream>
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.
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 .
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.
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With