use of this pointer in c++ code example
Example 1: What is This pointer? Explain with an Example.
Every object in C++ has access to its own address through an important pointer called this pointer.
The this pointer is an implicit parameter to all member functions.
Therefore, inside a member function, this may be used to refer to the invoking object.
Example:
#include <iostream>
using namespace std;
class Demo {
private:
int num;
char ch;
public:
void setMyValues(int num, char ch){
this->num =num;
this->ch=ch;
}
void displayMyValues(){
cout<<num<<endl;
cout<<ch;
}
};
int main(){
Demo obj;
obj.setMyValues(100, 'A');
obj.displayMyValues();
return 0;
}
Example 2: c++ pointers
#include <iostream>
using namespace std;
int main () {
int var = 20;
int *ip;
ip = &var;
cout << "Value of var variable: ";
cout << var << endl;
cout << "Address stored in ip variable: ";
cout << ip << endl;
cout << "Value of *ip variable: ";
cout << *ip << endl;
return 0;
}
Example 3: c++ pointers
#include <iostream>
using namespace std;
int main ()
{
int firstvalue, secondvalue;
int * mypointer;
mypointer = &firstvalue;
*mypointer = 10;
mypointer = &secondvalue;
*mypointer = 20;
cout << "firstvalue is " << firstvalue << '\n';
cout << "secondvalue is " << secondvalue << '\n';
return 0;
}
Example 4: pointer in c++
int* pointVar, var;
var = 5;
pointVar = &var;
cout << *pointVar << endl;
In the above code, the address of var is assigned to the pointVar pointer.
We have used the *pointVar to get the value stored in that address.
Example 5: this in c++
#include <iostream>
class Entity
{
public:
int x, y;
Entity(int x, int y)
{
Entity*const e = this;
this->x = x;
this->y = x;
}
int GetX()const
{
const Entity* e = this;
}
};
int main()
{
Entity e1(1,2);
}
Example 6: pointers c++
baz = *foo;