Search⌘ K
AI Features

Discussion: How Many Degrees?

Explore how C++ initializes class members through initializer lists and default constructors. Understand why multiple objects may be constructed, the role of temporary objects, and how default member initializers simplify code across constructors.

We'll cover the following...

Run the code

Now, it’s time to execute the code and observe the output.

C++
#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 ...