Example: Suppose we are developing a simple graphical interface:
We have windows and controls. What we want:
- There is a base window class that implements GUI functionality that is hidden from the user.
- From the base window, the user inherits a specific window.
- There is a button class, the instance of which the user can add to his window.
- The user can transfer the method of his window to the button, and it will be executed when clicking on this button.
I am interested in how to reach the last point.
Similarity of pseudo-code:
class BaseWindow; class Button { public: Button(BaseWindow* parent) { parent->AddButton(this); } void SetBehavior(/*Owners pointer and owner's methos*/) { /* Save Owner pointer and owner's method*/ } void Clicked(/*coords*/) { if(/*coords == my coords*/) { /*Call Owner's method*/ } } }; class BaseWindow { vector<Button*> Buttons; WindowClicked(/*coords*/) { for (std::vector<Button*>::iterator it = Buttons.begin(); it != Buttons.end(); ++it) { it->Clicked(/*coords*/); } } public: void AddButton(Button* butt) { Buttons<<butt; } }; class UserWindow:public BaseWindow { Button MyButton; public: void FunctionForButton(Button* butt){ cout<<"Say Hello, my sweet button";} UserWindow():MyButton(this) { MyButton.SetBehavior(/*Put here my Function for Button and my pointer*/); } };