I’m learning how to make programs using Qt. My question is about 3 things i’m not very good at: pointers, objects and “new()”.
Look: (Dialog is a class)
//start of code...
...
private:
Dialog *mDialog; //Dialog is a class
...
void MainWindow::on_activationNew_window_triggered()
{
mDialog = new Dialog(this); // Explain me this "this"
}
...
//end of code
Explain me how that line works, what “this” does (or is) exacly.
All i know is mDialog is a class for a window, and when the scope ends, the window closes, so he makes that pointer and uses new, because it will use a stack memory, that means it won’t close the window when the scope ends.
If you want to watch the part of the video he is making and explaining this (maybe i wasnt clear enough) here is the video (Start at 8:07):
http://www.youtube.com/watch?v=wUH_gu2HdQE&feature=relmfu
Tnks for any help!
As others have said, “this” refers to the object from where it’s called. Just like:
If you write
obj_X will have a variable of the name “this”. It will be used to access itself, and is most used in passing a class object to another method/class/anything.
Now, about Qt 🙂
Every Qt Object has a parent. That’s used for a lot of Qt’s inner workings, but it’s like an object owns another. To specify what is the parent object, and what’s the child, you send the parent’s address to the child’s constructor.
So, you could also do
Dialog mDialog(this);
This means that thing has nothing to do with the “new” operator. So let’s get to it:
“this” is sent to mDialog’s constructor, to specify that it has a parent. And it’s parent is the object pointed by “this”. You could also do it like
It’s that simple :). Get your c++ book and read more about constructors, and also get more Qt tutorials on the internet. Good luck!