When declaring objects in c++ -
What is the difference between
MyClass myObj (a,b,c);
(I understand this as invoking the constructor that takes three arguments)
vs.
MyClass myObbj{a,b,c};
Not sure what the curly brackets here mean?
As a reference I am using the following code
// Inertial Navigation EKF
NavEKF EKF{&ahrs, barometer, sonar};
AP_AHRS_NavEKF ahrs{ins, barometer, gps, sonar, EKF};
1. Is the use of curly brace as in NavEKF EKF{&ahrs, barometer, sonar}; part of c++ standard. gcc 4.6.1 complains that - Function definition does not declare parameters.
2. Given AP_AHRS_NavEKF ahrs;
AP_Baro barometer;
RangeFinder sonar;
2A. Why would the compiler complain about this
NavEKF EKF(&ahrs, barometer, sonar);
but allow this
NavEKF EKF(AP_AHRS_NavEKF &ahrs, AP_Baro barometer, RangeFinder sonar);
The basic intent is that they usually mean the same thing. The big difference is that curly braces eliminate the "most vexing parse" where you tried to define an object, but end up actually declaring a function instead.
So, NavEKF EKF{&ahrs, barometer, sonar};
is usually going to be equivalent to NavEKF EKF(&ahrs, barometer, sonar);
. However, if you had something like: NavEKF EKF();
vs. NavEKF EKF{};
they're different--NavEKF EKF();
declares a function named EKF that takes no parameters and returns a NavEKF
, whereas NavEKF EKF{};
does what you'd (probably) usually expect, and creates a default-initialized object named EKF
of type NavEKF
.
There are cases, however, where there's ambiguity about how to interpret things, and the ambiguity is resolved differently depending on whether you use parentheses or braces. In particular, if you use curly braces, and there's any way to interpret the contents as an initializer_list, that's how it'll be interpreted. If and only if that fails, so it can't be treated as an initializer_list, it'll look for an overload that takes the elements in the braces as parameters (and at this point, you get normal overload resolution, so it's based on the best fit, not just "can it possibly be interpreted to fit at all?")
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