Regarding for This Ptr.

S

skishorev

What is the use of This ptr.Follow the code snippet.

class this_pointer {
int data1;
public:

int getdata()
{
return this->data1;
}

void setdata(int newval)
{
data1 = newval;
}

};

Here two functions setdata and getdata. one is ' This Ptr', and one is
with out.
Exactly whats happening here. What is the use of This Pointer here.

Thanks &Regards,
Kishore.
 
B

Bo Persson

What is the use of This ptr.Follow the code snippet.

class this_pointer {
int data1;
public:

int getdata()
{
return this->data1;
}

void setdata(int newval)
{
data1 = newval;
}

};

Here two functions setdata and getdata. one is ' This Ptr', and one
is
with out.
Exactly whats happening here. What is the use of This Pointer here.

There is nothing in particual happening here. :)

The use of this-> has no effect here, it merely indicates that we want
to access a member of the class. In this case we would of course do
that anyway.

The original coder might have belived that it is more obvious this
way, or perhaps he just didn't think much about it. It is just two
ways to write this piece of code.


Bo Persson
 
M

Maxim Yegorushkin

Bo said:
There is nothing in particual happening here. :)

The use of this-> has no effect here, it merely indicates that we want
to access a member of the class. In this case we would of course do
that anyway.

The difference is that accessing the member variable through this
pointer restricts the scope of name lookup to this class or base
classes, while accessing it without this pointer also makes name lookup
also consider namespace scopes. IOW, if you move data1 member outside
the class scope to the outer scope getdata() function will break, while
setdata() won't.
 

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

No members online now.

Forum statistics

Threads
473,770
Messages
2,569,584
Members
45,075
Latest member
MakersCBDBloodSupport

Latest Threads

Top