Re: this
Priya Mishra wrote:
hi all,
Please any one help me out in understanding the "this" pointer in c++,
Please let me know the basic idea behind this, with very small
example.
I am not able to understand by the book language, I know C but some
what weak in C++
An easy way to understand it is to convert a class with member functions
into a struct without member functions, so you can see what a member
function actually is. e.g.
class Foo
{
public:
int i;
void f()
{
printf("%d\n", i);
}
};
Now, converting that to C code gives us:
struct Foo
{
int i;
};
void Foo_f(Foo* this)
{
printf("%d\n", this->i);
}
Now, in C++ when you do:
Foo foo;
foo.i = 1;
foo.f();
it is basically handled similarly to the C code:
Foo foo;
foo.i = 1;
Foo_f(&foo);
Conceptually, the object you are calling the member function on is
passed as a hidden parameter to the function, named "this". The final
piece of the puzzle is that, in a C++ member function, when you access a
name that the compiler works out is a member, it automatically puts a
"this->" in front.
So see that C++ classes and member functions are really just "syntatic
sugar" for C structs and normal functions, though obviously, for
example, inheritance and virtual functions complicate the issue, though
these can also be simulated in C code (indeed, the first C++ compiler
actually just converted C++ code into C code, using similar translations
to the one I demostrated above).
Tom