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!
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!
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(){};
};
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.
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.