Pointers to objects

Pointers to objects

Instead of statically allocating space for objects via MyClass o; we can dynamically allocate memory for objects using pointers. To dynamically allocate the memory for a new object use the new operator followed by a delete operator:

#include <iostream>
MyClass{
public:
	int x;
	void printX(){
		std::cout << "X is:" << std::endl;
	}
};

int main(){
	MyClass* p = new MyClass;
	p->x = 123;
	p->printX();
	delete p;
}

The arrow operator -> is used to access class members through an object pointer.

Smart pointers

Nowadays we prefer the use of smart pointers such as std::unique_ptr and std::shared_ptr instead of raw pointers:

#include <iostream>
#include <memory>
class MyClass{
public:
	int x;
	void printX(){
		std::cout << "X is:" << std::endl;
	}
};

int main(){
	std::unique_ptr<MyClass> p = std::make_unique<MyClass>();
	p->x = 123;
	p->printX();
}

This way we don't have to worry about manually releasing the allocated memory. Notice the absence of a delete statement. When pointer goes out of scope the memory is automatically released.