Thread: Having a class function call a function outside the class

  1. #1
    Registered User
    Join Date
    Jul 2005

    Having a class function call a function outside the class

    This is a bit hard to explain, and i'm not even sure this is possible in C++, but here it goes.

    Imagine I have a class "Level" for a tetris game. One function in this class is called "CheckLines" and it checks if there are any lines in the level and then removes them.

    In the main program I have another function, "onLineFound", which, for example, plays a sound effect and adds 10 point to the score.

    Now everytime "CheckLines" finds a line, I want it to call "onLineFound", but I do not want "onLineFound" to be part of the "Level" class (because the class is platform independent and playing a sound is not).

    Note that I could solve this particular example in other ways, but I'm looking for the method, not the solution


  2. #2
    Registered User
    Join Date
    Jun 2005
    The method is to ensure there is a prototype for the function you wish to call visible to the compiler at the point you wish to call it.
    void onLineFound();   //   this declaration may be in a header file
    void Level::CheckLines()
       // equivalent to above, but more explicit
    The above assumes both the class member function and the function being called accept no arguments and return void.

  3. #3
    Toaster Zach L.'s Avatar
    Join Date
    Aug 2001
    You could use a callback function, via function pointers. However, a better solution (in my opinion) would be to write your method as a functor (a struct with overloaded operator( ) to behave like a function), and pass that to your class. If swapping the function out is no issue, then use grumpy's solution.
    The word rap as it applies to music is the result of a peculiar phonological rule which has stripped the word of its initial voiceless velar stop.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Getting an error with OpenGL: collect2: ld returned 1 exit status
    By Lorgon Jortle in forum C++ Programming
    Replies: 6
    Last Post: 05-08-2009, 08:18 PM
  2. <Gulp>
    By kryptkat in forum Windows Programming
    Replies: 7
    Last Post: 01-14-2006, 01:03 PM
  3. Problem with Visual C++ Object-Oriented Programming Book.
    By GameGenie in forum C++ Programming
    Replies: 9
    Last Post: 08-29-2005, 11:21 PM
  4. Is it possible to have callback function as a class member?
    By Aidman in forum Windows Programming
    Replies: 11
    Last Post: 08-01-2003, 11:45 AM
  5. Interface Question
    By smog890 in forum C Programming
    Replies: 11
    Last Post: 06-03-2002, 05:06 PM