C++ cast syntax - c++

I've never seen the following cast syntax:
int var = int(1.0);
int is a base type so I'm wondering: is it equivalent to
int var = (int)1.0;
?

The two notations are equivalent(in the case of primitive types). Just a side note: please use static_cast in c++ instead of C-style casting. Does not make too much difference here but this is a bad habit.
For complex types first one would be calling a constructor while the second one is calling a casting operator and thus they may have quite different logic.

The first call is a constructor call.. The second is casting. They are basically the same.

Both solutions are syntactically correct and equivalent methods of explicit type casting.
http://www.cplusplus.com/doc/tutorial/typecasting/

Related

C++ casting for C-style downcasting

When working with a C API that uses C-style inheritance, (taking advantage of the standard layout of C-structs), such as GLib, we usually use C-style casts to downcast:
struct base_object
{
int x;
int y;
int z;
};
struct derived_object
{
base_object base;
int foo;
int bar;
};
void func(base_object* b)
{
derived_object* d = (derived_object*) b; /* Downcast */
}
But if we're writing new C++ code that uses a C-API like this, should we continue to use C-style casts, or should we prefer C++ casts? If the latter, what type of C++ casts should we use to emulate C downcasting?
At first, I thought reinterpret_cast would be suitable:
derived_object* d = reinterpret_cast<derived_object*>(b);
However, I'm always wary of reinterpret_cast because the C++ standard guarantees very little about what will happen. It may be safer to use static_cast to void*:
derived_object* d = static_cast<derived_object*>(static_cast<void*>(b))
Of course, this is really cumbersome, making me think it's better to just use C-style casts in this case.
So what is the best practice here?
If you look at the specification for C-style casts in the C++ spec you'll find that cast notation is defined in terms of the other type conversion operators (dynamic_cast, static_cast, reinterpret_cast, const_cast), and in this case reinterpret_cast is used.
Additionally, reinterpret_cast gives more guarantees than is indicated by the answer you link to. The one you care about is:
§ 9.2/20: A pointer to a standard-layout struct object, suitably converted using a reinterpret_cast, points to its initial member (or if that member is a bit-field, then to the unit in which it resides) and vice versa.
If you want to use a cast notation I think using the C++ type conversion operators explicitly is best. However rather than littering casts all over the code you should probably write a function for each conversion (implemented using reinterpret_cast) and then use that.
derived_object *downcast_to_derived(base_object *b) {
return reinterpret_cast<derived_object*>(b);
}
However, I'm always wary of reinterpret_cast because the C++ standard
guarantees very little about what will happen.
C++-style casts are no less safe than C-style casts, because C-style cast is defined in terms of C++-style casts.
5.4.4 The conversions performed by
— a const_cast (5.2.11),
— a static_cast (5.2.9),
— a static_cast followed by a const_cast,
— a reinterpret_cast (5.2.10), or
— a reinterpret_cast followed by a const_cast,
can be performed using the cast notation of explicit type conversion.
[...]
If a conversion can be interpreted in more than one of the ways listed above, the interpretation that
appears first in the list is used, even if a cast resulting from that interpretation is ill-formed.
The sad answer is that you can't avoid casts in code like you written, because the compiler knows very little about relations between classes. Some way or another, you may want to refactor it (casts or classes or the code that uses them).
The bottom line is:
If you can, use proper inheritance.
If you can't, use reinterpret_cast.
new C++ code that uses a C-API like this
Don't write new C++ code in a C style, it doesn't make use of the C++ language features, and it also forces the user of your wrapper to use this same "C" style. Instead, create a proper C++ class that wraps the C API interface details and hides them behind a C++ class.
should we continue to use C-style casts
No
or should we prefer C++ casts
Yes, but only when you have to.
Use C++ inheritance and virtual accessor functions (probably). Please show how you plan to use the derived object in func, this may provide a better answer for you.
If func expects to use the methods of the derived object, then it should receive a derived object. If it expects to use the methods of a base_object, but the methods are somehow changed because the pointer is to a derived_object, then virtual functions are the C++ way to do this.
Also, you want to pass a reference to func, not a pointer.
dynamic_cast, requires certain conditions to be met:
http://www.cplusplus.com/doc/tutorial/typecasting/
If you are just converting struct ptrs to struct ptrs and you know what you want, then static_cast, or reinterpret_cast may be the best?
However, if you truly are interested in writing C++ code, then the casts should be your last and final resort, since there are better patterns. The two common situations I would consider casting are:
You are interfacing with some event passing mechanism that passes a generic base class to an event handler.
You have a container of objects. The container requires it to contain homogenous types (i.e every element contains the same "thing"), but you want to store different types in the container.
I think dynamic_cast is exactly what you want.

In C++, what are the differences between static_cast<double>(a) and double(a)?

What are the differences between
int a;
// a gets some value
double pi = static_cast<double>(a)/3;
and
int a;
// a gets some value
double pi = double(a)/3;
Have you ever seen the latter? It seems to me I saw it in some snippet written by Stroustrup but I can't find the reference.
Someone may have thought they were constructing rather than casting. Consider:
some_fun(std::string("Hello"));
Many people think they're calling a constructor there when in fact they're doing a C-style cast. It just so happens that casting will look at constructors of the target type among the long list of other things it looks at and so here it eventually ends up invoking the constructor.
Functional notation casts have all the same weaknesses of the other kind of C cast:
Can inadvertently cast away constness
Can silently turn into a reinterpret cast
Are hard to differentiate with grepping tools.
Besides all that though, you're performing exactly the same operation in both cases.
The latter is referred to as the functional notation of explicit casting where you explicitly say a should be treated as a double. You can pretty much cast anything to any type using this technique.
The former is the preferred way to cast a type in C++. It does basic checking to see that the type you are casting to makes sense (child class pointer to a base class pointer, etc.). In addition, like in the example you show, you can perform implicit conversions. Technically the static_cast in your example is explicit, but the result of the operation (the assignment) is implicit.
There is no difference in terms of generated assembly code between static_cast<double> (a) and (double) a. The key advantage of cast notation, (type_id) cast_expression, is that it is more flexible. In one situation it might be the equivalent of a const_cast, in another, a static_cast, in yet another, a dynamic_cast, in yet another, a combination of const_cast and static_cast (or dynamic_cast).
This strength is also a weakness. Cast notation means different things in different places. Another disadvantage is that it is very easy to find xxx_cast<type_id> (cast_expression). Just search for _cast. It is very hard to find expressions that use cast notation.
using static_cast is a safe C++-style way, but (double) - unsafe old C-style way.
see here: Type Casting
int a;
//This is the old way of converting a variable from its type to a double
double pi = double(a)/3;
//This is the new way of converting a variable from its type to a double
double pi = static_cast<double>(a)/3;
From Walter Savitch's book, (Problem Solving with CPP, 10th Edition) page 222

What are the benefits of explicit type cast in C++?

What are the benefits of explicit type cast in C++ ?
They're more specific than the full general C-style casts. You don't give up quite as much type safety and the compiler can still double check some aspects of them for you.
They're easy to grep for if you want to try clean up your code.
The syntax intentionally mimics a templated function call. As a a result, you can "extend" the language by defining your own casts (e.g., Boost's lexical_cast).
Clarity in reading the code. There is not too much else of benefit, except for the cases where the compiler cannot infer the implicit cast at all, in which case you'd have to cast explicitly anyway.
The recommended way to cast in c++ is through dynamic_cast, static_cast, and the rest of those casting operators:
http://www.cplusplus.com/doc/tutorial/typecasting/
Notice that all typecasts are explicit in C++ and C. There are, in the language, no "implicit" typecasts. It's called "implicit conversions" and "explicit conversions", the latter of which are also called "casts".
Typecasts are most often used to inhibit warnings by the compiler. For instance if you have a signed and an unsigned value and compare them, the compiler usually warns you. If you know the comparison is correct, you can cast the operands to a signed type.
Another example is overload resolution, where type casts can be used to drive to the function to be called. For example to print out the address of a char, you can't just say cout << &c because that would try to interpret it as a C-Style String. Instead you would have to cast to void* before you print.
Often implicit conversions are superior to casts. Boost provides boost::implicit_cast to go by implicit conversions. For example the following relies on the implicit conversions of pointers to void*
cout << boost::implicit_cast<void*>(&c);
This has the benefit that it's only allowing conversions that are safe to do. Downcasts are not permitted, for example.
often used on void* to recover a implicitly known type. Especially common on embedded OS's for callbacks. This is a case where when you register for an event and maybe pass your "this" pointer as a context void*, then when the triggers it will pass you the void * context and you covert it back to the type the "this" pointer was.
Sometimes explicit casting avoids certain undesirable cirumstances by using explicit keyword.
class ExplicitExample
{
public:
ExplicitExample(int a){...}
}
ExplicitExample objExp = 'A';//No error.. call the integer constructor
Change as
explicit ExplicitExample(int a){ ... }
Now compile.
ExplicitExample objExp = 'A';
We get this error in VS2005.
error C2440: 'initializing' : cannot convert from 'char' to 'ExplicitExample'
Constructor for class 'ExplicitExample' is declared 'explicit'
To overcome this error, we have to declare as
ExplicitExample objExp = ExplicitExample('A');
It means as a programmer, we tell the compiler we know what we are calling. So compiler ignores this error.

What am I doing wrong with this pointer cast?

I'm building a GUI class for C++ and dealing a lot with pointers. An example call:
mainGui.activeWindow->activeWidget->init();
My problem here is that I want to cast the activeWidget pointer to another type. activeWidget is of type GUI_BASE. Derived from BASE I have other classes, such as GUI_BUTTON and GUI_TEXTBOX. I want to cast the activeWidget pointer from GUI_BASE to GUI_TEXTBOX. I assume it would look something like this:
(GUI_TEXTBOX*)(mainGui.activeWindow->activeWidget)->function();
This isn't working, because the compiler still thinks the pointer is of type GUI_BASE. The following bit of code does work, however:
GUI_TEXTBOX *textbox_pointer;
textbox_pointer = (GUI_TEXTBOX*)mainGui.activeWindow->activeWidget;
textbox_pointer->function();
I'm hoping my problem here is just a syntax issue. Thanks for the help :)
The problem is that casts have lower precedence than the . -> () [] operators. You'll have to use a C++ style cast or add extra parentheses:
((GUI_TEXTBOX*)mainGui.activeWindow->activeWidget)->function(); // Extra parentheses
dynamic_cast<GUI_TEXTBOX*>(mainGui.activeWindow->activeWidget)->function(); // C++ style cast
You should not be using the C style cast.
You need to use the C++ dynamic cast. This will then allow you to test that the object is actually a GUI_TEXTBOX before you call the method on it.
GUI_TEXTBOX* textboxPointer = dynamic_cast<GUI_TEXTBOX*>(mainGui.activeWindow->activeWidget);
if (textboxPointer)
{
// If activeWidget is not a text box then dynamic_cast
// will return a NULL.
textboxPointer->textBoxMethod();
}
// or
dynamic_cast<GUI_TEXTBOX&>(*mainGui.activeWindow->activeWidget).textBoxMethod();
// This will throw bad_cast if the activeWidget is not a GUI_TEXTBOX
Note the C style cast and reinterpret_cast<>() are not guaranteed to work in this situation (Though on most compilers they will [but this is just an aspect of the implementation and you are getting lucky]). All bets are off if the object assigned to activeWidget actually uses multiple inheritance, in this situation you will start to see strange errors with most compilers if you do not use dynamic_cast<>().
You just need more parentheses:
((GUI_TEXTBOX*)(mainGui.activeWindow->activeWidget))->function();
Actually, this would work too:
((GUI_TEXTBOX*)mainGui.activeWindow->activeWidget)->function();
As others noted:
((GUI_TEXTBOX*)(mainGui.activeWindow->activeWidget))->function();
The reason is that the -> operator has a higher precedence than the type casting.
I'll put another plug in here for Steve Oualline's rule from "Practical C":
There are fifteen precedence rules in
C (&& comes before || comes before
?:). The practical programmer reduces
these to two:
1) Multiplication and division come
before addition and subtraction.
2) Put parentheses around everything
else.
And a final note: downcasts can be dangerous, see Martin York's answer for information on using dynamic_cast<> to perform the cast safely.
It's a matter of order of operators (operator precedence). Consider the code you were trying that didn't work:
(GUI_TEXTBOX*)(mainGui.activeWindow->activeWidget)->function();
Here, the -> operator takes higher precedence than your cast. That's why your other code sample works. In the other sample, you explicitly cast first, then call the function. To make it more streamlined try adding another set of parenthesis so that the code looks like:
((GUI_TEXTBOX*)(mainGui.activeWindow->activeWidget))->function();
There are two strategies. One is "fail fast": If you cast to the wrong type, then you will have an exception thrown, so you will notice immediately that you cast to the wrong type. Another one is "run fast": No checking of the destination type of the cast is done. This cast should only be used if you know that you can't be wrong or if you don't have a polymorphic type with the base or the derived. I recommend the following depending on your needs (remember to keep const when you cast):
dynamic_cast<GUI_TEXTBOX&>(*mainGui.activeWindow->activeWidget).function();
Fail fast: throws std::bad_cast if you cast to the wrong type.
static_cast<GUI_TEXTBOX*>(mainGui.activeWindow->activeWidget)->function();
Run fast: Doesn't do a runtime check. So it won't fail fast. Rather, it will produce undefined behavior if you cast to the wrong type. Beware!
((GUI_TEXTBOX*)(mainGui.activeWindow->activeWidget))->function();
-> has a higher precedence than (cast), so the member access is being done before the cast. See here for operator precedence: http://www.cppreference.com/wiki/operator_precedence
As stated above, you need more parentheses.
if( GUI_TEXTBOX* ptr =
dynamic_cast<GUI_TEXTBOX *>(mainGui.activeWindow->activeWidget) )
{
ptr->function();
}
The reason you want to do that is because the pointer you are trying to cast may not actually point to a GUI_TEXTBOX object and you want to make sure it does before calling textbox methods on it. C++'s dynamic cast is what you need for this.

(int) ch vs. int(ch): Are they different syntaxes for the same thing?

In C++, is (int) ch equivalent to int(ch).
If not, what's the difference?
They are the same thing, and also the same as (int)(ch). In C++, it's generally preferred to use a named cast to clarify your intentions:
Use static_cast to cast between primitive types of different sizes or signednesses, e.g. static_cast<char>(anInteger).
Use dynamic_cast to downcast a base class to a derived class (polymorphic types only), e.g. dynamic_cast<Derived *>(aBasePtr).
Use reinterpret_cast to cast between pointers of different types or between a pointer and an integer, e.g. reinterpret_cast<uintptr_t>(somePtr).
Use const_cast to remove the const or volatile qualifiers from variables (VERY DANGEROUS), e.g. const_cast<char *>(aConstantPointer).
int(x) is called function-style cast by the standard and is the same as the C-style cast in every regard (for POD) [5.2.3]:
If the expression list is a single expression, the type conversion expression is equivalent (in definedness, and if defined in meaning) to the corresponding cast expression (5.4).
They are the same.
Konrad Rudolph is right. But consider that
(int) x <-- is valid syntax in C and C++
(int*) x <-- is valid syntax in C and C++
int (x) <-- is valid in C++, but gives a syntax error in C
int* (x) <-- gives a syntax error in both C and C++
Although the two syntaxes have the same meaning for int, the second, constructor-style syntax is more general because it can be used with other types in templates. That is, "T(x)" can be compiled into a conversion between primitive types (e.g., if T = int) or into a constructor call (if T is a class type). An example from my own experience where this was useful was when I switched from using native types for intermediate results of calculations to arbitrary-precision integers, which are implemented as a class.
The first is the C style, while the second is the C++ style.
In C++, use the C++ style.
It's worth noting that both styles of casting are deprecated in C++, in favor of the longer, more specific casting methods listed in Adam Rosenfield's answer.
If you want to be super-nasty, then if you write something like:
#define int(x) 1
Then (int)x has the meaning you expect, while int(x) will be 1 for any value of x. However, if anyone ever did this, you should probably hurt them. I can also quite believe that somewhere in the standard you are forbidden from #defining keywords, although I can't find it right now.
Except for that, very stupid, special case, then as said before, [5.3.2] says they are the same for PODs