Discussion: How Many Degrees?
Execute the code to understand the output and gain insights into constructors.
We'll cover the following
Run the code
Now, it’s time to execute the code and observe the output.
#include <iostream>struct Degrees{Degrees() : degrees_(0){std::cout << "Default constructer invoked\n";}Degrees(double degrees) : degrees_(degrees){std::cout << "Constructed with " << degrees_ << "\n";}double degrees_;};struct Position{Position() : latitude_{1} { longitude_ = Degrees{2}; }Degrees latitude_;Degrees longitude_;};int main(){Position position;}
Understanding the output
The Position
struct has two members of type Degrees
. One is initialized in the member initializer list, and one in the constructor body. So why do we see three Degrees
objects being constructed?
All class members are initialized before we get to the constructor body. If we explicitly initialize the member, as we do for latitude_
, that’s the initialization that’ll be used. If we don’t, as is the case for longitude_
, the member will instead be default-initialized, which is why we see the Default constructer invoked
line being printed. After all members have been initialized, we finally enter the constructor body, initialize a temporary Degrees{2}
, and then copy-assign it to the previously default-initialized longitude_
.
Note that instead of explicitly initializing the member in the member initializer list, we can use a default member initializer directly in the member declaration, as shown below:
#include <iostream>struct Degrees{Degrees() : degrees_(0){std::cout << "Default constructer invoked\n";}Degrees(double degrees) : degrees_(degrees){std::cout << "Constructed with " << degrees_ << "\n";}double degrees_;};struct Position{Position() { longitude = Degrees{2}; }Degrees latitude{1}; // Default member initializerDegrees longitude;};int main(){Position position;}
Using a default member initializer can be a good idea if we have several constructors. Then, we don’t have to remember to include that member in every member initializer list.
Level up your interview prep. Join Educative to access 70+ hands-on prep courses.