I understand that generally C-style casts are considered harmful. So, given a class Widget
class Widget{
public:
explicit Widget(Gizmo gizmo);
};
I could call a function like this:
functionThatTakesAWidget((Widget) gizmo);
using a C-style cast. Or I could write it using a function-style cast:
functionThatTakesAWidget(Widget(gizmo));
but this is exactly equivalent. So no better or worse. And If I really wanted to avoid a C-style cast I could write:
functionThatTakesAWidget(static_cast<Widget>(gizmo));
But given a class Doohickey:
class Doohickey {
public:
Doohickey(Gizmo left_gizmo, Gizmo right_gizmo);
};
I can't avoid writing:
functionThatTakesADoohickey(Doohickey(left_gizmo, right_gizmo));
I assume this is not considered a 'cast' at all? But what is the difference between this and a function-style cast? Why is this OK but a function-style cast is not?
The reasons for avoiding C-Style casts are:
While the function-style cast looks safer, it's actually a C-style cast in disguise, so it does not really add anything.
The driving reason behind being explicit is letting the compiler assert your assumptions, instead of silently doing (sometimes) the wrong thing.
IMHO, some purists go to far in their zeal though.
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