Chapter 2. Connecting your code to signals

Table of Contents

A simple example
Using a member function
Signals with parameters

A simple example

So to get some experience, lets look at a simple example...

Lets say you and I are writing an application which informs the user when aliens land in the car park. To keep the design nice and clean, and allow for maximum portability to different interfaces, we decide to use LibSigC++ to split the project in two parts.

I will write the AlienDetector class, and you will write the code to inform the user. (Well, OK, I'll write both, but we're pretending, remember?)

Here's my class:

class AlienDetector

    void run();

    sigc::signal<void> signal_detected;

(I'll explain the type of signal_detected later.)

Here's your code that uses it:

void warn_people()
    cout << "There are aliens in the carpark!" << endl;

int main()
    AlienDetector mydetector;
    mydetector.signal_detected.connect( sigc::ptr_fun(warn_people) );;

    return 0;

Pretty simple really - you call the connect() method on the signal to connect your function. connect() takes a slot parameter (remember slots are capable of holding any type of callback), so you convert your warn_people() function to a slot using the slot() function.

To compile this example from the downloadable example code, use:

g++ -o eg1 `pkg-config --cflags --libs sigc++-2.0`

Note that those `` characters are backticks, not single quotes. Run it with


(Try not to panic when the aliens land!)