Questions tagged [this-pointer]

The "this" pointer is a compiler-generated pointer during a function call that points to the object upon which that function gets called.

Multiple objects of the same class have identical data members in them. Whenever a function gets called on an object, only the data members of that particular object are changed. The compiler knows which object's data members to access and modify by use of a special pointer, known as the this pointer, which stores the object's address in memory.

Whenever a function gets called on an object, the compiler automatically creates the this pointer and sends it to the function. Because of this, there is no need to explicitly declare or pass this to the function.

this is a keyword in the C++ language and is used in conjunction with the arrow member operator -> when used within a class to access its data members and functions.

void myClass::myFunction()
{
  this->myVariable = 10;
}

Which is equivalent to:

void myClass::myFunction()
{
  myVariable = 10;
}

Sometimes, the object itself is returned using the this pointer:

void myClass::myFunction()
{
  ...
  return (*this);
}
139 questions
-3
votes
1 answer

How to return managed this pointer

This is probably a simple noob user-error, And I feel dumb not figuring this out myself. I have some old unmanaged code that I need to convert to managed c++ .net, because I want to Serialize the objects. My question is not about serialization…
-3
votes
1 answer

Physics vector constructor, magnitude and unit vector functions not working c++

I am writing a class called Vector which represents a 3-dimensional vector. I need a constructor which can take a pre-existing Vector object and create a new one from it. This is the constructor: Vector::Vector(const Vector &v1){ for(int i = 0;…
Tom Finet
  • 2,056
  • 6
  • 30
  • 54
-3
votes
2 answers

Why after dereferencing/deallocation of the dynamically created object, it's is still being referenced in c++?

#include #include using namespace std; class Marie{ public: int x; Marie(){ cout<<"created"; } ~Marie(){ cout<<"hii i am destructor"; } void ShowMarie() { cout<<"friends"; …
-5
votes
2 answers

I am unable to use a class variable as a default argument for the same class's function

I am well aware that line 7 is invalid . but I want to use the class variables as default argument to method(apple) . class trial{ public: int i=10 ; void apple(int i=this.i){ cout<
1 2 3
9
10