What am I doing wrong with this pointer cast? - c++

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.

Related

My teacher is not type-casting the same way as everyone else. Does anyone know what he is doing?

My teacher included the lines below in one of our examples of casting. c is an object of class Circle which inherits from class Point. In my search for an answer to the question "Can I cast an object of class Point to type Circle?" I found that he uses a different syntax than every website I've been on. The websites all use static_cast and dynamic_cast syntax. He won't be using static_cast and dynamic_cast on the test and I'm just wondering what he is using and how that operates.
Also, if you have an answer to whether I can cast a base object to a derived type, I thank you immensely.
output << "the center of the circle is at " << (Point) c;
// casting `Circle` object `c` with type `(Point)`, calls the first overloaded >stream insertion operator"
(Point)c is known as a "C-style" cast. This can basically be thought of as a brute force cast that does whatever it can to make the cast succeed. This means it could end up causing a static_cast a const_cast or even a reinterpret_cast.
When the C-style cast expression is encountered, the compiler attempts to interpret it as the following cast expressions, in this order:
const_cast
static_cast
static_cast followed by const_cast
reinterpret_cast
reinterpret_cast followed by const_cast
Source: https://en.cppreference.com/w/cpp/language/explicit_cast
And from Stroustrup himself:
Explicit type conversions (often called casts to remind you that they are used to prop up something broken) are best avoided.
and
C-style casts should have been deprecated in favor of named casts.
Stroustrup, Bjarne. A Tour of C++ (C++ In-Depth Series) (Kindle Location 7134). Pearson Education. Kindle Edition.
So the named casts are recommended. In practice I still encounter professional code using C-style casts simply because it makes code more succinct and readable and is -- if you know what you're doing -- normally equivalent to static_cast in the places its used. For what its worth I think C-style casts are okay if used for these reasons in a context that makes it obvious that it will result in a static_cast, and Stroustrup is coming from an overly object-oriented perspective in his general disdain for casting. But you should prefer the named casts.
Your teacher is probably using the C-style cast as a less scary-looking introduction to casting.
The answers so far didn't cover what (Point) c; actually does. Assuming Circle does not explicitly define operator Point:
This is the same as static_cast<Point>(c). It creates a temporary Point object which is initialized by Point's copy-constructor, with c as the argument. This works because the base class copy-constructor can, for better or worse, bind to a derived object.
To be clear, it is NOT a reference of any sort to the Point part of the Circle. It is making a copy of the Point part of the Circle. This is called slicing. It loses all the "Circle" part of the information.
I would advise not doing this. The code would be better off without the cast. I guess perhaps there is defined operator<< overloads for both Point and Circle and he wants to explicitly select the Point one; in that case you should use static_cast<Point&>(c) or the equivalent (Point&)c to view the circle instead of slicing it.
NB. Deriving Circle from Point in the first place is also suspicious; inheritance should represent an "is-a" relationship (not "has-a"); but a circle is not a point.
Further reading: What is object slicing?
That is a C-style cast and will use "c.operator Point()" if available, otherwise it will behave the same as "reintrepret_cast(c)"

C++ cast syntax

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/

Why can't you call functions on a pointer object?

Edit: sorry about the stupid title; by "pointer object" I think I mean dereferenced object pointer (if that's any clarification).
I'm new to C++, and I've been trying to get used to its idiosyncrasies (coming from Java).
I know it's not usually necessary, but I wanted to try passing an object by its pointer. It works, of course, but I was expecting this to work too:
void test(Dog * d) {
*d.bark();
}
And it doesn't. Why is this? I found out that I can do the following:
void test(Dog * d) {
Dog dawg = *d;
dawg.bark();
}
and it works flawlessly. It seems so redundant to me.
Any clarification would be appreciated. Thanks!
Imo . has precedence over dereference * , thus:
(*d).bark();
or, for pointers, as stated in other replies - use ->
d->bark();
be sure to check for null :)
Just to clarify the situation, you can use either (*pointer).member(), or pointer->member() -- a->b is equivalent to (*a).b.
That, of course, is assuming you're dealing with "real" (built-in) pointers. It's possible to overload operator-> to do something different. Overloads of operator-> are somewhat restricted though, which generally prevents people from doing too strange of things with them. The one thing you might run into (e.g., with old implementations of some iterators) is simply failing to support operator-> at all, so trying to use it will result in a compile error. Though such implementations are (mostly?) long gone, you might still see some (typically older) code that uses (*iterator).whatever instead of -> because of this.
You have to use the -> operator on pointers. The . operator is for non-pointer objects.
In your first code snippet, try d->bark();. Should work fine!
EDIT: Other answers suggest (*d).bark();. That will work as well; the (*d) dereferences the pointer (ie. turns it into a normal object) which is why the . operator works. To use the original pointer, simply d, you must use the -> operator as I described.
Hope this helps!
Its all in the parentheses:
(*d).bark();
Everyone is missing one point to answer: Operator Precedence.
The precedence of operator. is higher than that of (unary) pointer indirection (*) opeartor. That's why brackets are needed. It's just like putting parenthesis around + to get correct average:
int nAverage = (n1+n2) / 2;
For pointer indirection case, you are lukcy that compiler is giving you error!
You need to use -> operator when using pointers, i.e. code should be d->bark();.

Difference between static_cast<primitive_type>(foo) and primitive_type(foo) [duplicate]

I've heard that the static_cast function should be preferred to C-style or simple function-style casting. Is this true? Why?
The main reason is that classic C casts make no distinction between what we call static_cast<>(), reinterpret_cast<>(), const_cast<>(), and dynamic_cast<>(). These four things are completely different.
A static_cast<>() is usually safe. There is a valid conversion in the language, or an appropriate constructor that makes it possible. The only time it's a bit risky is when you cast down to an inherited class; you must make sure that the object is actually the descendant that you claim it is, by means external to the language (like a flag in the object). A dynamic_cast<>() is safe as long as the result is checked (pointer) or a possible exception is taken into account (reference).
A reinterpret_cast<>() (or a const_cast<>()) on the other hand is always dangerous. You tell the compiler: "trust me: I know this doesn't look like a foo (this looks as if it isn't mutable), but it is".
The first problem is that it's almost impossible to tell which one will occur in a C-style cast without looking at large and disperse pieces of code and knowing all the rules.
Let's assume these:
class CDerivedClass : public CMyBase {...};
class CMyOtherStuff {...} ;
CMyBase *pSomething; // filled somewhere
Now, these two are compiled the same way:
CDerivedClass *pMyObject;
pMyObject = static_cast<CDerivedClass*>(pSomething); // Safe; as long as we checked
pMyObject = (CDerivedClass*)(pSomething); // Same as static_cast<>
// Safe; as long as we checked
// but harder to read
However, let's see this almost identical code:
CMyOtherStuff *pOther;
pOther = static_cast<CMyOtherStuff*>(pSomething); // Compiler error: Can't convert
pOther = (CMyOtherStuff*)(pSomething); // No compiler error.
// Same as reinterpret_cast<>
// and it's wrong!!!
As you can see, there is no easy way to distinguish between the two situations without knowing a lot about all the classes involved.
The second problem is that the C-style casts are too hard to locate. In complex expressions it can be very hard to see C-style casts. It is virtually impossible to write an automated tool that needs to locate C-style casts (for example a search tool) without a full blown C++ compiler front-end. On the other hand, it's easy to search for "static_cast<" or "reinterpret_cast<".
pOther = reinterpret_cast<CMyOtherStuff*>(pSomething);
// No compiler error.
// but the presence of a reinterpret_cast<> is
// like a Siren with Red Flashing Lights in your code.
// The mere typing of it should cause you to feel VERY uncomfortable.
That means that, not only are C-style casts more dangerous, but it's a lot harder to find them all to make sure that they are correct.
One pragmatic tip: you can search easily for the static_cast keyword in your source code if you plan to tidy up the project.
In short:
static_cast<>() gives you a compile time checking ability, C-Style
cast doesn't.
static_cast<>() can be spotted easily
anywhere inside a C++ source code; in contrast, C_Style cast is harder to spot.
Intentions are conveyed much better using C++ casts.
More Explanation:
The static cast performs conversions between compatible types. It
is similar to the C-style cast, but is more restrictive. For example,
the C-style cast would allow an integer pointer to point to a char.
char c = 10; // 1 byte
int *p = (int*)&c; // 4 bytes
Since this results in a 4-byte pointer pointing to 1 byte of allocated
memory, writing to this pointer will either cause a run-time error or
will overwrite some adjacent memory.
*p = 5; // run-time error: stack corruption
In contrast to the C-style cast, the static cast will allow the
compiler to check that the pointer and pointee data types are
compatible, which allows the programmer to catch this incorrect
pointer assignment during compilation.
int *q = static_cast<int*>(&c); // compile-time error
Read more on:
What is the difference between static_cast<> and C style casting
and
Regular cast vs. static_cast vs. dynamic_cast
The question is bigger than just using whether static_cast<> or C-style casting because there are different things that happen when using C-style casts. The C++ casting operators are intended to make those different operations more explicit.
On the surface static_cast<> and C-style casts appear to be the same thing, for example when casting one value to another:
int i;
double d = (double)i; //C-style cast
double d2 = static_cast<double>( i ); //C++ cast
Both of those cast the integer value to a double. However when working with pointers things get more complicated. Some examples:
class A {};
class B : public A {};
A* a = new B;
B* b = (B*)a; //(1) what is this supposed to do?
char* c = (char*)new int( 5 ); //(2) that weird?
char* c1 = static_cast<char*>( new int( 5 ) ); //(3) compile time error
In this example (1) may be OK because the object pointed to by A is really an instance of B. But what if you don't know at that point in code what a actually points to?
(2) may be perfectly legal (you only want to look at one byte of the integer), but it could also be a mistake in which case an error would be nice, like (3).
The C++ casting operators are intended to expose these issues in the code by providing compile-time or run-time errors when possible.
So, for strict "value casting" you can use static_cast<>. If you want run-time polymorphic casting of pointers use dynamic_cast<>. If you really want to forget about types, you can use reintrepret_cast<>. And to just throw const out the window there is const_cast<>.
They just make the code more explicit so that it looks like you know what you were doing.
static_cast means that you can't accidentally const_cast or reinterpret_cast, which is a good thing.
Allows casts to be found easily in
your code using grep or similar
tools.
Makes it explicit what kind
of cast you are doing, and engaging
the compiler's help in enforcing it.
If you only want to cast away
const-ness, then you can use
const_cast, which will not allow you
to do other types of conversions.
Casts are inherently ugly -- you as
a programmer are overruling how the
compiler would ordinarily treat your
code. You are saying to the
compiler, "I know better than you."
That being the case, it makes sense
that performing a cast should be a
moderately painful thing to do, and
that they should stick out in your
code, since they are a likely source
of problems.
See Effective C++ Introduction
It's about how much type-safety you want to impose.
When you write (bar) foo (which is equivalent to reinterpret_cast<bar> foo if you haven't provided a type conversion operator) you are telling the compiler to ignore type safety, and just do as it's told.
When you write static_cast<bar> foo you are asking the compiler to at least check that the type conversion makes sense and, for integral types, to insert some conversion code.
EDIT 2014-02-26
I wrote this answer more than 5 years ago, and I got it wrong. (See comments.) But it still gets upvotes!
C Style casts are easy to miss in a block of code. C++ style casts are not only better practice; they offer a much greater degree of flexibility.
reinterpret_cast allows integral to pointer type conversions, however can be unsafe if misused.
static_cast offers good conversion for numeric types e.g. from as enums to ints or ints to floats or any data types you are confident of type. It does not perform any run time checks.
dynamic_cast on the other hand will perform these checks flagging any ambiguous assignments or conversions. It only works on pointers and references and incurs an overhead.
There are a couple of others but these are the main ones you will come across.
static_cast, aside from manipulating pointers to classes, can also be used to perform conversions explicitly defined in classes, as well as to perform standard conversions between fundamental types:
double d = 3.14159265;
int i = static_cast<int>(d);

(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