CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 12 of 12
  1. #1
    Join Date
    Jul 2007
    Posts
    5

    Passing "this" to methods

    Hello. I've been studying OOP for the pass year. Only I'm struggling to find out what why/when you have to pass the "this" pointer to some methods.

    For example:

    Code:
    #include <QtGui> 
    #include "myqtapp.h"
     
    // if we include <QtGui> there is no need to include every class used: <QString>, <QFileDialog>,...
     
    myQtApp::myQtApp(QWidget *parent)
    {
        setupUi(this); // this sets up GUI
     
        // signals/slots mechanism in action
        connect( pushButton_browse, SIGNAL( clicked() ), this, SLOT( getPath() ) ); 
        connect( pushButton_do, SIGNAL( clicked() ), this, SLOT( doSomething() ) ); 
        connect( pushButton_clear, SIGNAL( clicked() ), this, SLOT( clear() ) ); 
        connect( pushButton_about, SIGNAL( clicked() ), this, SLOT( about() ) ); 
    }
     
     
    void myQtApp::getPath()
    {
        QString path;
        
        path = QFileDialog::getOpenFileName(
            this,
            "Choose a file to open",
            QString::null,
            QString::null);
     
        lineEdit->setText( path );
    }
     
     
    void myQtApp::doSomething()
    {
        int value1, value2;
        Qt::CheckState state;
        QString str;
     
        textEdit->append( "Path to file: " + lineEdit->text() );
     
        value1 = spinBox1->value();
        value2 = spinBox2->value();
     
        textEdit->append( "Number 1 value: " + QString::number(value1) );
        textEdit->append( "Number 2 value: " + QString::number(value2) );
     
        state = checkBox->checkState();
     
        str = "Checkbox says: ";
        if ( state == Qt::Checked ) str += "yes"; 
        else str += "no";
        textEdit->append( str );
     
        textEdit->append( "ComboBox current text: " + comboBox->currentText() );
        textEdit->append( "ComboBox current item: " + QString::number(comboBox->currentIndex()) );
    }
     
     
    void myQtApp::clear()
    {
        textEdit->clear();
    }
     
     
    void myQtApp::about() 
    {
        QMessageBox::about(this,"About myQtApp",
                    "This app was coded for educational purposes.\n"
                    "Number 1 is: " + QString::number(spinBox1->value()) + "\n\n"
                    "Bye.\n");
    }
    Why does this code pass the various this pointer to other methods? I know the this pointer is the address of the invoking object, but what I'm trying to get at is why pass the address of an object (THIS) to the methods that are defined within the same class.
    Last edited by phil128; October 1st, 2010 at 04:44 AM.

  2. #2
    Lindley is offline Elite Member Power Poster
    Join Date
    Oct 2007
    Location
    Seattle, WA
    Posts
    10,895

    Re: Passing "this" to methods

    If the method in question is static, then it won't get an implicit this, so if you want access to a particular object you need to pass it.

  3. #3
    Join Date
    Aug 2000
    Location
    West Virginia
    Posts
    7,721

    Re: Passing "this" to methods

    In this case, it merely indicates which object receives the signal.

  4. #4
    Join Date
    May 2009
    Posts
    2,413

    Re: Passing "this" to methods

    Quote Originally Posted by phil128 View Post
    Only I'm struggling to find out what why/when you have to pass the "this" pointer to some methods.
    The usual reason an object passes this is that it wants to register itself as listener in some kind of message system. The object then expects to be notified when something it has subscribed to happens.

    I'm not familiar with QT but it seems you're registering the object with QT's "signal/slot" mechanism. Since you've passed the this pointer to QT it knows what object to notify when the event you subscribed to has happened.

  5. #5
    Join Date
    Jul 2005
    Location
    Netherlands
    Posts
    2,042

    Re: Passing "this" to methods

    Quote Originally Posted by phil128 View Post
    Why does this code pass the various this pointer to other methods? I know the this pointer is the address of the invoking object, but what I'm trying to get at is why pass the address of an object (THIS) to the methods that are defined within the same class.
    Because, in general, something other than this may be passed in certain situations. E.g. a signal may be handled by an object owned by the object that makes the connection.
    Cheers, D Drmmr

    Please put [code][/code] tags around your code to preserve indentation and make it more readable.

    As long as man ascribes to himself what is merely a posibility, he will not work for the attainment of it. - P. D. Ouspensky

  6. #6
    Join Date
    Jul 2007
    Posts
    5

    Re: Passing "this" to methods

    Could someone please show me some examples of passing THIS pointer to methods please? And the advantages please. I'm coming from C background and i'm finding it difficult to adapt to certain aspects of the WHOLE this pointer.

    Driving me nuts

  7. #7
    Lindley is offline Elite Member Power Poster
    Join Date
    Oct 2007
    Location
    Seattle, WA
    Posts
    10,895

    Re: Passing "this" to methods

    I think the code in your first post is a great example. While I haven't used QT's signals/slots mechanism, the basic idea is simply that you're registering a callback, and you need to pass user data as well which will be passed back to the callback when it is invoked. This is a common setup in C-based APIs like GTK+'s signal mechanism.

    Let's say you want to just print out the string "WindowClicked!\n" whenever a certain event occurs, and that there's a C function register() which takes an event specifier, a callback function pointer, and user data:

    register("window-clicked-event", printf, "WindowClicked!\n");

    But let's say that instead of a free-standing function like printf, you want the callback to invoke a method of a particular C++ object. Well, unfortunately, this register() routine is C-based and so doesn't know how to deal with functors, only function pointers. And a method call on an object cannot be converted to a standard function pointer, because it needs to know which object it is operating on and thus has a "hidden" extra parameter (this).

    One solution to this dilemma is to write a helper function which calls the method for you:
    Code:
    class MyClass
    {
        public:
            void doSomething();
    };
    
    void helper(void *data)
    {
        MyClass *c = static_cast<MyClass*>(data);
        c->doSomething();
    }
    
    int main()
    {
        MyClass M;
        register("window-clicked-event", helper, &M);
    }
    Straightforward, right? But what if you don't think you should need to call this register() function from main() every time you create an M. Perhaps you think that should happen automatically when an M is created. In that case, you could do:

    Code:
    void helper(void *);
    
    class MyClass
    {
        public:
            MyClass();
            void doSomething();
    };
    
    MyClass::MyClass()
    {
        register("window-clicked-event", helper, this);
    }
    
    void helper(void *data)
    {
        MyClass *c = static_cast<MyClass*>(data);
        c->doSomething();
    }
    
    int main()
    {
        MyClass M;
    }
    Basically, the "this" pointer is used whenever an object needs to tell some other bit of code about itself.

  8. #8
    Join Date
    Jul 2007
    Posts
    5

    Re: Passing "this" to methods

    BLOODY HELL!!!!!!!!!!!!!! Thank you very much! I've fully understood the example that you've showed me :-D. I still don't know why, when I've come across C++ tutorials/books on the "this" pointer, they never explain passing them to methods only using them in getters/setters.

    Thanks alot!

  9. #9
    Lindley is offline Elite Member Power Poster
    Join Date
    Oct 2007
    Location
    Seattle, WA
    Posts
    10,895

    Re: Passing "this" to methods

    Using the this pointer is rarely necessary in getters and setters because it will be implicitly used, unless you have a local variable or parameter with the same name as a class member variable, in which case this->var can be used to disambiguate the two. However, there's no *harm* in using this->var in other cases, except the extra typing.

  10. #10
    Join Date
    Jul 2007
    Posts
    5

    Re: Passing "this" to methods

    I've heard using the this pointer is good(only syntactically), when you inheriting from an object that contains getters and setters?

    Btw am I correct in saying, that the this pointer is only used for callbacks, alot like the function pointers in C i.e.

    (call back)int (*func)(int,int);

  11. #11
    Lindley is offline Elite Member Power Poster
    Join Date
    Oct 2007
    Location
    Seattle, WA
    Posts
    10,895

    Re: Passing "this" to methods

    Quote Originally Posted by phil128 View Post
    I've heard using the this pointer is good(only syntactically), when you inheriting from an object that contains getters and setters?
    I don't see offhand why it would matter there.

    Btw am I correct in saying, that the this pointer is only used for callbacks, alot like the function pointers in C i.e.

    (call back)int (*func)(int,int);
    Be careful with words like "only". The this pointer can be used any time you need to refer to the current object. Have you see code written like this in C:

    Code:
    void my_class_set_name(const my_class *obj, const char *name)
    {
        obj->myname = strdup(str);
    }
    
    my_class M;
    my_class_set_name(&M, "Ted");
    Well, the equivalent C++ might be
    Code:
    void MyClass::setName(const std::string &name)
    {
        this->myname = name;
    }
    
    MyClass M;
    M.setName("Ted");
    Here, the use of "this" is completely optional, but is included to show the relationship between how C might pass an explicit object pointer to work on, and C++ would do it implicitly by invoking the method on a particular object.

  12. #12
    Join Date
    Jun 2009
    Location
    France
    Posts
    2,513

    Re: Passing "this" to methods

    "this" is also used when you write template classes with parent template classes. The parent methods won't be "seen" by the compiler unless they are prefixed by this->.

    But this is much more of a syntactic detail than a design detail.
    Is your question related to IO?
    Read this C++ FAQ article at parashift by Marshall Cline. In particular points 1-6.
    It will explain how to correctly deal with IO, how to validate input, and why you shouldn't count on "while(!in.eof())". And it always makes for excellent reading.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured