Callbacks in C++


simple solution

#include <iostream.h>
class Button;
class CdPlayer
{
public:
  void buttonPushed(Button* pButton_)
  { 
    if (pButton_ == _pPlayButton)
      this->playButtonPushed(pButton_);
    else if (pButton_ == _pStopButton)
    this->stopButtonPushed(pButton_);
  }
 
  void setPlayButton(Button* pButton_) {_pPlayButton = pButton_;}
  void setStopButton(Button* pButton_) {_pStopButton = pButton_;}
  void playButtonPushed(Button*) {cout << "PLAY" << endl;}
  void stopButtonPushed(Button*) {cout << "STOP" << endl;}

private:
  Button* _pPlayButton;
  Button* _pStopButton;
};
//----------------------------------------
class Button
{
public:
  Button(CdPlayer* pCdPlayer_): _pCdPlayer(pCdPlayer_){}
  void push() {_pCdPlayer->buttonPushed(this);}
private:
  CdPlayer* _pCdPlayer;
};
//----------------------------------------
main()
{
  CdPlayer aCdPlayer;
  Button playButton(&aCdPlayer);
  Button stopButton(&aCdPlayer);
  aCdPlayer.setPlayButton(&playButton);
  aCdPlayer.setStopButton(&stopButton);

  playButton.push();
  stopButton.push();

  return 0;
}

[View/Add Comments]


Callbacks in C++
Copyright © 1996-2000 Paul Jakubik
Created: 26 July 1996. Last update: 26 November 2000.
pauljakubik@yahoo.com