What if your program could grow and shrink its memory exactly when needed, without wasting a single byte?
Why new operator in C++? - Purpose & Use Cases
Imagine you want to create a program that needs to store a list of user names, but you don't know how many users there will be when you write the code.
You try to create a fixed-size array to hold the names, but sometimes it's too small, and other times it wastes a lot of memory.
Using fixed-size arrays means you either run out of space or waste memory.
Changing the size later means rewriting code and copying data manually, which is slow and error-prone.
This makes your program less flexible and harder to maintain.
The new operator lets you ask the computer to give you exactly the amount of memory you need while the program is running.
This means you can create arrays or objects that fit your data perfectly, even if you don't know the size beforehand.
int users[10]; // fixed size, may be too small or waste memory
int* users = new int[userCount]; // size decided at runtime
You can build flexible programs that adapt to changing data sizes without wasting memory or crashing.
Think of a photo gallery app that loads images based on how many photos a user has. Using new, it can create just enough space to hold all photos, no matter the number.
Fixed-size arrays limit flexibility and waste memory.
new lets you allocate memory dynamically during program execution.
This makes programs more adaptable and efficient.