-3

I know that this will seem a very basic question, but actually it is not something obvious because of the use of pointers, scopes and GTK especific types of variables and others. I really was not able to find an answer.

I have got to divide the GUI related part of a Gtkmm program into functions, but something seems to be wrong.

To make it clear, here is an example, There is the WORKING code in CODE1.cpp, and it must be divided into something similar to CODE2.cpp (not yet working).

The first one is a window containing only a label, the second is the same, but the label is created inside a function.

Where is the error? What is missing? Any tip or help would be appreciated.

Codes mentioned are the following:

CODE1.cpp:

#include <gtkmm.h>

int main (int argc, char *argv[])
{
    Glib::RefPtr<Gtk::Application> app = Gtk::Application::create(argc, argv, "Ejemplo");

    Gtk::Window     ventana;
    Gtk::Label      labela;
    labela.set_text("perrito");
    ventana.add (labela);
    ventana.show_all ();

    return app->run(ventana);
}

CODE2.cpp:

#include <gtkmm.h>

Gtk::Label etiqueta (string x)
{
    Gtk::Label  labela;
    labela.set_text(x);
    return ( labela );
}

int main (int argc, char *argv[])
{
    Glib::RefPtr<Gtk::Application> app = Gtk::Application::create(argc, argv, "Ejemplo");
    Gtk::Window     ventana;

    etiqueta("perrito");

    ventana.add (labela);
    ventana.show_all ();
    return app->run(ventana);
}
Ffff
  • 73
  • 1
  • 3
  • 14

1 Answers1

1

I guess your problem is that the Gtk::Label does not appear. That's because:

a) You are creating it as a local variable in the scope of the function and it is then released at the end of the function. Maybe you mean to use new (with Gtk::manage()) and return a Gtk::Label* instead of a Gtk::Label.

b) You don't use the return value from your function. There is no labela variable in your main() function.

I don't mean to sound harsh, but you need to read your compiler warnings and you need to read a beginner's C++ book. It's hard to learn C++ just by guessing or by hoping that it's like other languages such as Java.

murrayc
  • 2,103
  • 4
  • 17
  • 32
  • I know several people who had good experiences with "Accelerated C++: Practical Programming by Example", though you would have to learn about C++11 afterwards. http://www.amazon.com/gp/product/020170353X/ref=as_li_tl?ie=UTF8&camp=1789&creative=390957&creativeASIN=020170353X&linkCode=as2&tag=murrayswebpages&linkId=WPRF5SV6UEIUEIQC – murrayc Oct 15 '15 at 19:12
  • Ok, thanks for your answer, not taken as harsh... Would you be kind to recommend a book that could help acquiring the kind of knowledge needed to work with stuff like this. Because I have read some C++ books, but they are either, too basic or too advanced. – Ffff Oct 15 '15 at 19:18
  • Ok, thanks for your quick answer. I will surely look for this book. – Ffff Oct 15 '15 at 19:19