Please can someone explain?

Hi all,

I am starting to do some programming with classes. I have the following class definition:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#ifndef GTKMESSAGE_H_
#define GTKMESSAGE_H_
#include <gtkmm.h>

class messageWindow : public Gtk::Window
{
public:
	messageWindow();
	virtual ~messageWindow();
protected:
	void btn_click();
	Gtk::Button btn;	
};


#endif /*GTKMESSAGE_H_*/ 


When I start to write the constructor though it is in this format:
1
2
3
4
5
messageWindow::messageWindow()
 : btn("Click here.")
{
//some code here
}

I'm not too sure what the " : btn("click here")" is. Is it a re initialization of the variable btn?

Thanks for your advice,
Matt
As it seems, it is an instance of Gtk::Button, which could be an method or a class, I am not completly sure, have to go thru c++ class reference again;) But one thing is certain, it is not an variable, for cariable can not have parameters.

Gregor
It means that the string "Clicke here." is passed as an argument to the constructor for Gtk::Button.

All member variables must be fully constructed before the body of the messageWindow contructor. If you need to pass arguments to a constructor for a member object, this is how you do it.

If you have more than one, they are separated by commas, and they must come in the same order as they are defined in the class.
You may also pass parameters to the constructor of Gtk::Window (the base class). This must be first in the list. Many people consider it good practice to always have the base class constructor in the list. Others think that all member variables should always be in the list. If you have a long list, it's common to split it over several lines:

1
2
3
4
5
MessageWindow::MessageWindow()
: Gtk::Window(),
  btn("Click here.")
{
}


Note that I changed the class name to MessageWindow. I recommend to always start class names with a capital letter.
So when i have defined btn in my header file, it actually hasn't created the instance of it? and therefore hasn't ran the constructor of the Gtk::Button class?

Thanks,
Matt
Last edited on
You have defined btn in the header file +inside+ the MessageWindow class. This means that the button will be created when you create a MessageWindow. When you do that, an instance will be created of the btn. It has nothing to do with the initializer list discussed above.

The initializer list is used to pass parameters to the Button constructor. If you don't want to pass any parameters, you don't need btn in the list (although it's sometimes recommended anyway), but an instance of it is created in any case.

Note: If the Button class doesn't have a default constructor, meaning one that takes no arguments. You must have in the initializer list.
Last edited on
Ah right, many thanks for clearing that up for me :)
Matt
Topic archived. No new replies allowed.