<aside> 💡

Can we use pointers with object? Answer is yes.

</aside>

Pointer to Object

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
}

Pointers to Objects in Objects

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
}
  1. We use new to dynamically allocate memory for a complex number. Its address is assigned to the pointer to complex number called Px.
  2. The 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

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

1000025593.jpg

Dynamic Memory Allocation for Arrays

int arr[4] = {1, 2, 3, 4};