<aside> 💡
Can we use pointers with object? Answer is yes.
</aside>
class complexNum{
public:
double real;
double img;
complexNum(double re, double im){
real = re;
img = im;
}
};
int main(){
complexNum x(3, 4); // we use the constructor to creat a complex number
x.real = 2; // we set the real part to 2 now instead of 3
complexNum* p; // we created a pointer to complexnumber called p
p = &x; // now p points to the original complexNum object called x
p->real = 7; // we go through pointer p to reach and change the real part
(*p).img = 7 // we go to what's at p to change the imaginary operator
}
p is created and stored on the stack.We can have multiple pointers in the code.
class complexNum{
public:
double real;
double img;
complexNum* next; // this is a pointer-to-complexnumber called next
complexNum(double re, double im){
real = re;
img = im;
next = nullPtr;
}
~complexNum(){
if (next != nullPtr){
delete next;
}
}
};
int main(){
complexNum* Px = new complexNum(5, 5); // 1. new dynamically allocates and returns ptr
Px->next = new complexNum(); // 2. we dynamically create a new complex number
Px->next->real = 8; // this changes the real part of the second complex number
delete Px; // this does NOT cause a memory leak because of our destructor magic
}
new to dynamically allocate memory for a complex number. Its address is assigned to the pointer to complex number called Px.next pointer from the first complex number no longer points at NULL. Instead, it now points to the brand new complex number we just created in line 2.Double Pointers:
int** p2p; // a pointer to a pointer-to-int called p2p
int *p, *q; // two pointer-to-int called p and q
p = new int; // we dynamically allocate an int and assign its address to p
*p = 5; // we assign 5 to what's-at-p
p2p = &p // p2p has the address of p
q = *p2p // q has what's-at-p2p, meaning q now has the address of p
*q = 8 // what's-at-q is now 8, meaning the 5 becomes an 8
delete p; // frees the space pointed to by p, which was the new integer

int arr[4] = {1, 2, 3, 4};
arr is an alias, and it stores the address to the list of elements in the arraycout << arr;, we will see the address of arr[0]cout << *arr;, we will see 1cout << *(arr+1);, we will see 2