Search code examples
c++wxwidgets

C++, Passing custom class object in wxWidgets


Can someone explain me how to pass a custom class object to another function in wxWidgets? I have a wxDialog class called AddUser which contains a void type OnButtonClick function that creates an object of a custom class "User". How can I pass that object to another OnButtonClick function that is located in Main class?


Solution

  • One important thing to know (in case you don't already) about wxDialog is that it is quite okay to create them on the stack (most wxWidgets windows should be created on the heap).

    This means that your dialog instance remains available even after it has been closed by the user pressing "Ok". You can test for user responses by the following code:

    ... existing method ...
    
    AddUser dialog (this);
    
    if (dialog.ShowModal() == wxID_OK)
    {
        ... process new user ...
    }
    

    Because the dialog is still instantiated, you can include a method in your dialog code that returns the new user as follows:

    User AddUser::GetUser ()
    {
        return newUser;
    }
    

    However, you should of course be careful where the new user is actually created. For example, if the new user object is created locally in the dialog, then you will need to make a copy of it (as the above example will do). If it is created on the heap (which I wouldn't advise) then you can return a pointer. A third alternative would be to pass a reference to the GetUser method so the dialog method looks like this:

    bool AddUser::GetUser (User& user)
    {
        // Make sure that all fields are valid. Simple example given, but
        // should be more complete.
        if (TextName->GetValue() != "" && TextSurname->GetValue() != "")
        {
            user.setName(TextName->GetValue());
            user.setSurname(TextSurname->GetValue());
    
            return true;
        }
            return false;
    
        return newUser;
    }
    

    And the call looks like this:

    void wxBiblioFrame::OnButAddUserClick(wxCommandEvent& event)
    {
        AddUser dialog(this);
        myUserDialog dialog (this);
    
        myUserClass newUser;
    
        if (dialog.ShowModal() == wxID_OK)
        {
            if (dialog.GetUser (newUser))
            {
                ... process and store the new user ...
            }
            else
            {
                ... handle the error ...
            }
        }
    
        // NOTE: no need to Destroy() the dialog.
    }
    

    By the way, unless your user class is huge, I wouldn't be too concerned making copies of the object from an efficiency point of view. Creating and closing the dialog is likely to dwarf any time taken in making a copy.