Question

I'm a newbie, and I'm trying to understand the this pointer; can anyone can tell me to what does the "this pointer" point in C++?

To base address of the class?

Is this pointer in struct or union have the same meaning as in a class?

Était-ce utile?

La solution

'this' usually refers to the instance of the object that calls a particular method of a class,union,structure or a function.

when you have same names for different variables, then 'this' is used to differentiate between them.

class stu
{
int roll_no;
string name;

public:
void input(int roll_no,string name)
{
name=this->name;
roll_no=this->roll_no;
}


}

stu obj=new stu();
obj.input("47","harry");

Here, the 'this' tells that the 'name' is of the 'obj' that calls the method. Thus 'this' specifies the instance of the variable which belongs to the class object. Also remember, when you want answers to theoretical questions, try to google them first. Hope this helps.

Autres conseils

A struct and a class are the same thing in c++ apart from struct having default members default to public.

A union doesn't have a this pointer.

The easiest way to think of a this pointer, is an internal pointer to the class you are writing code for.

Outside of a class (a pointer to an object called b)

b->c();

Inside the class:

this->c();
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top