Using GUI member variables in a subclass

Do you have a question about makefiles, a compiler or IDE you are using and need to know how to set it up for wxWidgets or why it doesn't compile but other IDE's do ? Post your questions here.
User avatar
doublemax
Moderator
Moderator
Posts: 14976
Joined: Fri Apr 21, 2006 8:03 pm
Location: $FCE2

Re: Using GUI member variables in a subclass

Post by doublemax » Sun Jun 21, 2020 7:57 am

...is sharing the current gui in multiple modules.
You don't. At least not in the way you imagine. If any class wants to communicate with your GUI, you pass a pointer to the GUI instance to that class (usually to its constructor). And all communication is done with public methods, don't access member variables directly.

At first sight that sounds like a waste of time and a lot of unnecessary typing, but the benefits will be clear when your project gets bigger.

Imagine this simple "House" class:

Code: Select all

class House
{
public:
  House () {
    m_windows_open = false;
    m_heater_level = 0;
  }

  bool m_windows_open;
  int m_heater_level;
}
The member variables are public can manipulated directly from any other class that has a pointer to a "House" instance.

But now you want to make sure that the heater is not on when the windows are open. You could make that check everywhere in your code where you manipulate these variables. However, it's easier to do that in the House itself.

Code: Select all

class House
{
public:
  House () {
    m_windows_open = false;
    m_heater_level = 0;
  }
  
  void OpenWindows() {
    m_windows_open = true;
    SetHeaterLevel(0);
  }
  
  void CloseWindows () {
    m_windows_open = false;
  }
  
  void SetHeaterLevel( int value ) {
    if(value > 0 )
      CloseWindows();
    m_heater_level = value;
  }
  
protected:
  bool m_windows_open;
  int m_heater_level;
}
Now the windows and the heater can only be accessed through the public methods, OpenWindows, CloseWindows and SetHeaterLevel. And the house itself makes sure that the heater is not on when the windows are open. And even if the house class changes internally, as long as the public interface remains the same, you don't have to make any changes to other classes.
Use the source, Luke!

Post Reply