This-pointer from constant methods



  • Hello,

    I tried to access "this" from inside a constant method (QAbstractItemModel::data()) a few days ago... but when I tried it, I got a compiler-error telling me that I am not allowed to use this in a const method. I thought about something like const_cast, but of course I cannot cast the method... anyway, I found a way better solution that avoids this problem.
    But I am still wondering, if this would have been possible with some tricks...

    Does anybody know a technique to access "this" from a const method? Just for interest...



  • Are you sure you didn't forget the class scope when defining the method, and therefore you didn't have access to this (and not because the method is const); because a const method method actually has access to this.
    @
    class TestClass
    {
    public:
    void methodA() const;
    void methodB() const;
    }

    void TestClass::methodA()
    {
    // has access to this
    qDebug() << this;
    }

    void methodB()
    {
    // has no access to this, due to not beeing a member of TestClass
    qDebug() << this;
    }
    @
    If not, please provide some code on your own.



  • I had a look at it again, the class scope is set correctly, and I was able to access this now, but I got some error (don't remember the exact message) when trying to use this.
    The problem wasn't "this" but that I tried to access a non const method from "this"... when I access a const method it works, otherwise it says this-pointer cannot be converted from 'const CMyModel' to 'CMyModel &'



  • If you are inside a const method, you may not call non const member functions, even if you use this as a pointer.

    The following code blocks do exactly the same and behave the same:

    @
    void TestClass::methodA() const
    {
    foo();
    }
    @

    @
    void TestClass::methodA() const
    {
    this->foo();
    }
    @

    you can const_cast a this pointer to a non const pointer of the same class type, but be sure you do nothing, you are not allowed. Typically, if you have to call a non const function from a const one, you have a problem in the design.



  • As I said, I already found a better way, that avoids this call...
    I just found it interesting to know ;)
    thanks


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.