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 :)

Answers


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

Need Your Help

FileNotFoundException: Playing an mp3 file with Java/Eclipse

java eclipse nullpointerexception mp3 libraries

I am trying to play an mp3 using an external mp3 library and everything is fine until it comes to finding the file.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.