Here’s my understanding of pointers in the form of quick program to test.
/*
main.cpp : Defines the entry point for the console application.
Program to test understanding of how pointers work in C++
*/
#include <iostream>
// My Cheeky class, defined here for breivity
class MyCheekyClass {
public:
void SayHi();
};
void MyCheekyClass::SayHi()
{
std::cout << "HI THERE" << std::endl;
return;
}
int main()
{
int ival = 42;
std::cout << "The value of ival is: " << ival << std::endl;
// A pointer holds the address of another object.
// We get the address of an object by using the & operator (address-of operator)
// Define p as a pointer to int and initialise p to be the address that points to the ival object
int* p = &ival;
// The type of the pointer must match the type of the original object
// double* invalidPointer = &ival; // This will not compile as ival is type int not a double
// We can use the * operator (deference operator) to access the object.
// *p should equal 42
std::cout << "The deferenced value of *p is: " << *p << std::endl;
// We can assign the ival object by asigning to the result of the deference
*p = 300;
std::cout << "Assign new value of 300 \n";
// ival and *p should return 300
std::cout << "The new value of ival is: " << ival << std::endl;
std::cout << "The new deferenced value of *p is: " << *p << std::endl;
MyCheekyClass Cheeky;
// Define a pointer that holds the address of the Cheeky object
MyCheekyClass* CheekyP = &Cheeky;
// To access the method SayHi() we can deference the pointer then call the method
(*CheekyP).SayHi();
// Can also use the access operator: ->
CheekyP->SayHi();
return 0;
}