Search⌘ K
AI Features

Solution: Detect Narrowing Conversion

Explore how designated initializers work in C++ and how they help detect narrowing conversions during class member initialization. Understand the compile-time errors caused by narrowing conversions and the differences between C and C++ designated initialization behaviors. This lesson helps you write safer, more reliable initialization code by catching type-related issues early.

We'll cover the following...

Solution

C++
#include <iostream>
struct Point2D {
int x;
int y;
};
class Point3D {
public:
int x;
int y = 1;
int z = 2;
};
int main() {
std::cout << '\n';
Point2D point2D{.x = 1, .y = 2.5};
Point3D point3D{.x = 1, .y = 2, .z = 3.5f};
std::cout << "point2D: " << point2D.x << " " << point2D.y << " ";
std::cout << "point3D: " << point3D.x << " " << point3D.y << " "
<< point3D.z << '\n';
std::cout << '\n';
}

Line 18 and line 19 ...