this

P

Priya Mishra

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++

Thanks
Priya
 
A

Alf P. Steinbach

* Priya Mishra:
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++

Just ignore it.
 
A

al pacino

if you 'know' java/python its analogous to 'self'....
or better still follow any good book on c++..chek out earlier topics on
'good' books on c++
 
A

al pacino

al said:
if you 'know' java/python its analogous to 'self'....
or better still follow any good book on c++..chek out earlier topics on
'good' books on c++

err sorry ppl top posted by mistake....
 
J

Jim Langston

Priya Mishra said:
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++

Thanks
Priya

this simply points to the instance of the object that the method is being
called on. Usually it is not needed. Sometimes it is (such as to return a
pointer to itself). An example may illistrate.

#include <iostream>
#include <string>

class MyClass
{
public:
MyClass* GivePointer() { return this; }
};

void main()
{
MyClass* MyInstance = new MyClass();

MyClass* ObjectPointer = MyInstance->GivePointer();

if ( MyInstance == ObjectPointer )
std::cout << "Equal Pointers" << std::endl;
else
std::cout << "Not Equal Pointers" << std::endl;

std::string wait;
std::cin >> wait;
}

The output of this is:
Equal Pointers.

Again, usually you do not need to know the pointer of the instance you are
calling a method on. Sometimes you do though. If you don't need it, don't
worry about it.
 
M

Murali Krishna

Priya said:
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++

Thanks
Priya

It is required to know about 'this' pointer. I feel I know very little
about 'this' but I will still try to explain.
I believe you are beginner.

this is a pointer. pointer to what? To the same Class's instantiation
or Say object.
Precisely the address of object for which it is being called.

How can you talk about a pointer to the same object with out creating
that object?
What actually happens inside a function if you are using 'this'?

These were the questions I got when I first learnt C++.
They are actually very silly, aren't they?
Most people ignore that and they keep programming with out knowing..
like me.

Jim Langston gave a good example. This example is to know that.. the
object instance and 'this' will have the same address.

Suppose say if Myclass's object m..

MyClass m; if &m starts with address 1000, for example, this pointer
will also have the same address.

Another way to find out is go to debugging and see if 'this' and &m has
the same address location.

The point we have to understand is 'this' means the pointer to that
object (that is accessing).

You may get confused when working with two are more objects.. for
example..
MyClass m1, m2;

What is 'this' for m1 and m2. Though this is silly for advanced
programmers, This confusion is common for beginners.

I'll give an example.. (It is not actually required to use 'this' in
this example (see.. We have used this in 'in this example' sentence.
this in a class gives the same meaning))

class Complex // say a complex number // I hope you know complex
numbers
{ // we are going to add two complex numbers
private:
int i; // real part
int j; // imaginary part
public:
Complex() {i = 0; j = 0; }
Complex(int real, int imag)
{
i = real;
j = imag;
}
// Hope you know some thing about operator overloading.
Complex operator+(Complex c)
{ // With out overloading '+' operator, we cannot add Two 'Complex'
numbers (Objects).
Complex temp;// temp object will call default constructor now
temp.i = this->i + c.i; // or temp.i = i + c.i;
temp.j = this->j + c.j;
return temp;
}
void print()
{
cout << endl;
cout << "real : " << i; // or this->i;
cout << " imaginary : " << j << endl;
}
}; // You know we have created new data type called Complex

int main(int argc, char* argv[])
{
Complex c1(10, 20);
c1.print();
Complex c2(30, 40);
c2.print();
Complex c3; // call default constructor i = 0, j = 0
c3 = c1 + c2; // c3 = c1.operator+(c2); // both mean the same
c3.print();
return 0;
}

Consider the function operator+ . We have used..
temp.i = this->i + c.j;

which means..

i of temp object = the current object's i + i of the c Object

so 'this' will have current object's information.

now if you give..

c1 = c3 + c2;

now 'this' will point to c3.

ok now, who created 'this'? I didn't create it.

As soon as you create a class, you get a 'this' pointer. like a default
constructor, default destructor and a default

assignment operator that we get by default.

You can see we have not overloaded '=' operator anywhere. You get that
by default.

As I said before this example doesn't require 'this' pointer.

We can write the above statement as follows..

temp.i = i + c.j;

which implicitly mean this->i

temp.i = this->i + c.j;

because this is a pointer (pointer to the current object) we have to
use -> operator for accessing it's data and functions

try (*this).i;

I think now you have understood what this means. now we will understand
where we require 'this'.

I am taking an example of Windows CDC class and CWnd class.
You have similar kind of thing in java's applet and Graphics classes

Suppose that you are writing a class that is derived from CWnd.

CWnd is a class in Windows that is responsible for creating a window.
Now the explorer (if you are using windows) you are

seeing would have been created with that class.

Ok you derived a class from CWnd to create a window and you want to do
some graphics work in that. For that we have a class

called CDC (Device context). In java we have similar kind of class (I
dont remember).

The device context is resposible for printing something on to the
window.

now we create an object for CDC..
CDC dc;

CDC has a function to draw a line
CDC::LineTo(int x, int y); // x, y position to where the line should be
drawn
// draws from the default 0,0 position

but to draw a line dc has to know to which window the line has to be
drawn. now dc doesn't know that.

So while creating we specify that dc has to be created for the window
we are accessing.

so we create like as follows..

CDC dc(this);

for example..

class CMyWnd : public CWnd
{
.
.
.
// Some data and functions

void OnLButtonDown(Some parameters....)
{
CDC dc(this); // dc takes the current window
dc.LineTo(50, 50); // draw the line to the current window.
}
};

This is just an example. If it is confusing to you, just leave it.
What I mean to say is we can pass 'this' pointer as an argument. There
by we send the address of the current object that is being accessed.
this is where 'this' pointer is really useful.

And as in Jim's example, you can return the this pointer which means we
are returning the pointer to the current class's type. (current
object's address)

There is lot about 'this'. I told very little.

--bye
Murali Krishna.
 
T

Tom Widmer

Priya said:
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
 
M

Murali Krishna

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.

yes I saw it in "Thinking in C++" book.
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).

This is the first I am reading this. Thanks for that.
-- Murali Krishna.
 
F

Frederick Gotham

Priya Mishra posted:
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++


A few people have given some very good explanations.

I'd like to give you my own point of view.

I don't like trying to learn about concepts which are not tangible, (such
as references and virtual functions). I don't know if it's just my own
way of thinking, but I like to have a firm, tangible grasp on a concept,
and I get a bit anxious when things get a bit fuzzy and metaphysical.

I like C's way of doing things -- very tangible. I particularly like that
everything is passed by value, because my mind has a firm grasp on that
concept.

C++ has more elaborate features such as references, and virtual member
functions, and these concepts fuzzle my head when I try to think about
them, especially things like "return by reference" and "pass by
reference".

Solution... ? Emulate the feature using C code, in the aim of attaining a
tangible sort of grasp of what's going on.

Here's some C++ code:

class ArbitraryClass {
public:

int i;

void NonConstMethod()
{
i = 7;

this->i = 8;
}

void ConstMethod() const {}
};

int main()
{
ArbitraryClass obj;

obj.NonConstMethod();
}


And here's my equivalent C code:


struct ArbitraryClass {

int i;

};


void NonConstMethod( ArbitraryClass * const this )
{
i = 7;

this->i = 8;
}

void ConstMethod( const ArbitraryClass * const this ) const {}


int main()
{
ArbitraryClass obj;

NonConstMethod( &obj );
}


Maybe that would give you an idea of where "this" comes from?


[Here come's a nit-pick:]

If it were real C code, I'd code it slightly differently because of
inconsistencies between C and C++:

(1) typedef struct Name { /* Stuff */ } Name;

instead of:

struct Name { /* Stuff */ };


(2) int main(void)

instead of:

int main()
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,432
Messages
2,571,682
Members
48,796
Latest member
Greg L.

Latest Threads

Top