c++ function pointer code example
Example 1: 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 2: pointer in c++
int a = 5;
cout << a;
int a = 5;
int *ab;
ab = &a;
cout << ab;
Example 3: what is this pointer in c++
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.
Friend functions do not have a this pointer,
because friends are not members of a class.
Only member functions have a this pointer.
Example 4: c++ pointers
#include <iostream>
using namespace std;
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;
double* bigger_array = new double[2 * n];
for (int i = 0; i < n; i++)
{
bigger_array[i] = account_array[i];
}
delete[] account_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;
return 0;
}
Example 5: 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 6: 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.