tags:

views:

155

answers:

3

Hi, straight and clear as the title says :)

Background:

I run into some tutorial and I realized that I missed some things... So, I would really appreciate if anyone can point out any must_know_facts with an example.

Thanks!

A: 
this

is a const pointer to the current obj of class.

Small Trick

To access non-const member functions (from const member functions)

You can do it by using 'this' keyword only

You cannot access a non-const member function (or member variable) from a const member function.

So suppose you are in a situation like this:

class C
{
public:
    void func() const
    {
       x = 10;    // fails
       foo(){};     // fails
    }

private:
    int x;  // I know you could have made x mutable
    void foo();  //but what about a nonconst member function?
};

Thats Illegal to do.

So therefore you can leverage 'this' pointer to remove the constness just to call a nonconst member function or nonconst member variable.

Like this:

class C
{
public:
    void func() const
    {
        const_cast<C *>(this)->x = 10;
        const_cast<C *>(this)->foo();
    }

private:
    int x;
    void foo(){};
};
bits
-1: This is terrifyingly bad advice. You are correct that using a `const_cast` allows the code in your second example to compile, but it is inherently dangerous to do so. "a write operation through the pointer...resulting from a `const_cast` that casts away a const-qualifier may produce undefined behavior" (C++03 §5.2.11/7).
James McNellis
Can you please share where can I refer such information like (C++03 §5.2.11/7), so that I can improve my understanding of c++?
bits
@bits: cf. http://stackoverflow.com/questions/81656/where-do-i-find-the-current-c-or-c-standard-documents A good C++ book is probably a better place to learn most things about C++, though. The standard is not easy to comprehend.
James McNellis
Would this be the correct document to refer:http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1256.pdf ? Please let me know, because I am trying to look for (C++03 §5.2.11/7); and I can't find anything in section 5.2...
bits
+3  A: 

When using a class method in a C style callback, you need to use a 'trampoline' function which can be a free function or a static class method. The reason is the this pointer is passed implicitly to all non-static class methods which a callback cannot do.

Pass the this pointer as the data parameter to the callback registration. Your trampoline function can cast that back to your class type then invoke that instance's actual method.

This is also useful for using a class method as a thread function.

Amardeep
+1  A: 

this can be NULL. It isn't supposed to happen. If it does it shows a bug in the program. Still, for debugging you should know that it can happen.

Zan Lynx