c++ this pointer code example
Example 1: c++ pointers
#include <iostream>
using namespace std;
int main () {
int var = 20; // actual variable declaration.
int *ip; // pointer variable
ip = &var; // store address of var in pointer variable
cout << "Value of var variable: ";
cout << var << endl; //Prints "20"
// print the address stored in ip pointer variable
cout << "Address stored in ip variable: ";
cout << ip << endl; //Prints "b7f8yufs78fds"
// access the value at the address available in pointer
cout << "Value of *ip variable: ";
cout << *ip << endl; //Prints "20"
return 0;
}
Example 2: c++ pointers
#include <iostream>
using namespace std;
// isualize this on http://pythontutor.com/cpp.html#mode=edit
int main()
{
double* account_pointer = new double;
*account_pointer = 1000;
cout << "Allocated one new variable containing " << *account_pointer
<< endl;
cout << endl;
int n = 10;
double* account_array = new double[n];
for (int i = 0; i < n; i++)
{
account_array[i] = 1000 * i;
}
cout << "Allocated an array of size " << n << endl;
for (int i = 0; i < n; i++)
{
cout << i << ": " << account_array[i] << endl;
}
cout << endl;
// Doubling the array capacity
double* bigger_array = new double[2 * n];
for (int i = 0; i < n; i++)
{
bigger_array[i] = account_array[i];
}
delete[] account_array; // Deleting smaller array
account_array = bigger_array;
n = 2 * n;
cout << "Now there is room for an additional element:" << endl;
account_array[10] = 10000;
cout << 10 << ": " << account_array[10] << endl;
delete account_pointer;
delete[] account_array; // Deleting larger array
return 0;
}
Example 3: pointer in c++
int* pointVar, var;
var = 5;
// assign address of var to pointVar
pointVar = &var;
// access value pointed by pointVar
cout << *pointVar << endl; // Output: 5
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 4: this in c++
#include <iostream>
class Entity
{
public:
int x, y;
Entity(int x, int y)
{
Entity*const e = this;// is a ptr to the the new instance of class
//inside non const method this == Entity*const
//e->x = 5;
//e->y =6;
this->x = x;
this->y = x;
}
int GetX()const
{
const Entity* e = this;//inside const function this is = const Entity*
}
};
int main()
{
Entity e1(1,2);
}
Example 5: pointers c++
baz = *foo;