Casting a Pointer to the Frame

If you are using the main C++ distribution of wxWidgets, Feel free to ask any question related to wxWidgets development here. This means questions regarding to C++ and wxWidgets, not compile problems.
Post Reply
spflanze
Earned some good credits
Earned some good credits
Posts: 130
Joined: Tue Feb 15, 2011 10:02 pm

Casting a Pointer to the Frame

Post by spflanze » Thu May 14, 2020 3:53 am

I have several wxGrid derived objects in a frame. The wxGrid derived class has a method I added, and need to debug. As a debugging aid I would like to set a break point when the method is called for a specific instance of that wxGrid derived class. I attempted to do that using the this pointer, and setting the break point within an if statement's compound statement:

Code: Select all

if( this == (TIA_DesignerFrame*)GetParent()->A1GridinData )
{
  // Break point on some dummy statement here
}
Where:
A1GridinData: is an instance of the wxGrid derived class
TIA_DesignerFrame: Is the wxFrame derived class

The error I get is:

Code: Select all

C:\Engineering_Software\TIA_Designer_2020-03-20\src\Utilities.cpp|1160|error: 'class wxWindow' has no member named 'A1GridinData'
I attempted to solve this by adding the statement:

Code: Select all

#include "../TIA_DesignerMain.h"
to Utilities.h , and I got many syntax errors.

Is there a way to get a pointer to the frame, and caste it to type "TIA_DesignerFrame*", short of declaring a temporary global variable which would be set to "this" in TIA_DesignerFrame's constructor?

PB
Part Of The Furniture
Part Of The Furniture
Posts: 2387
Joined: Sun Jan 03, 2010 5:45 pm

Re: Casting a Pointer to the Frame

Post by PB » Thu May 14, 2020 5:28 am

You should use C++'s dynamic_cast to cast a pointer to the base class to the derived class. E.g., if you have a pointer to a wxWindow (such as returned from GetParent()) where you know it is an instance of TIA_DesignerFrame (which is also derived from wxWindow, with few other classes in between), you would do

Code: Select all

TIA_DesignerFrame* frame = dynamic_cast<TIA_DesignerFrame*>(GetParent());
If the conversion could not be made, because the parent was not a TIA_DesignerFrame instance (or was nullptr), frame will contain nullptr. Otherwise, you now have an instance of TIA_DesignerFrame and can access its members.

And obviously, the file where the code above is run must have an access to TIA_DesignerFrame declaration (i.e., include the header where it is declared).

Post Reply