Re: C++-classes.



David Larsson wrote:

Hi.

How do you get this to work.

/* Class Definition */
class GtkClass
{
 public:
   void GtkClass();
   void Test();
 private:
   GtkWidget *button;
};

This class declaration is wrong. Constructors do not have a return value, void or non-void.

As other people pointed out , you can't pass a class method to a GTK C signal connection function because of the hidden "this" pointer. C doesn't know about "this". A global C-like signal handler was suggested:

void clicked_cb(GtkButton *button, GtkClass *c)
{
        c->Test();
}

but this is wrong (Sorry!). It's bad C++ programming to use global functions and variables. You don't need them. If you think you do then you need re-think your progam's design.

All is not lost. You can do exactly what you want. This is how:

class GtkClass
{
   GtkWidget *button; // private by default

   static void Test(); // no this pointer for static methods

public:
   GtkClass();
};

GtkClass::GtkClass()
{
   button = gtk_button_new();

gtk_signal_connect(GTK_OBJECT(button), "clicked", GTK_SIGNAL_FUNC(&GtkClass::Test), 0); // C++ doesn't use NULL. It's a C macro.
}

It doesn't matter how you order your public, protected and private declarations. I prefer private at the top because that is the default for classes, so you don't need to use the private keyword. Then protected and last public.

To be able to pass the address of a class method to a C function the class method must be declared static. The static modifier in a class declaration means there is only one copy of the function or variable generated. That means all instances of the class will use the same function body and/or variable. This is what you want for a signal handler.

When you pass a static class method to a C function you have to specify its entire scope, that is "namespace::class::method". For your GtkClass it's "GtkClass::Test" because your not using a namespace. Just an after thought: It's fine to declare functions and variables outside a class as long as they are in a namespace.

I hope that helped,

Jeff Franks




[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]