- The most C++-ish way to create a
struct
is struct_name{value1, value2}
. And you don't need to declare your own constructor.
If you really want to use a constructor, use the one with initializer syntax. Here is the difference. Let's consider a structure with two fields. So it looks like: {one, two}
. When you use initializer syntax, you create the needed struct immediately before the actual constructor code you wrote between curly braces. So it looks like: {1, 2}
(we have values now). However, when you initialize those fields inside a constructor's body, it will create a structure with default values first and then change them. So it looks like: {0, 0} ...constructor is working... {1,2}
.
Ok, the last thing about it is parameter declaration. You should use constant references as it prevents a programmer from changing those parameters inside the function body, and these variables are passed by reference and not copied. Let's look at two examples:
void fun1(int a, int b);
void fun2(const int& a, const int& b);
fun1
here copies those two parameters before using them inside the body. However, fun2
gets only references to the variables and work with their values directly. Also, because of the const
, you cannot change them, so it is completely safe.
- Modern C++ does not like the
new
operator. We use it only inside constructors and calling the delete
operator in destructors. However, it is not recommended to use the new operator in other cases as it is much harder to prevent memory leaks, and it violates the RAII idiom. If you really must use raw pointers, then consider putting them inside smart pointers.