Menu
×
     ❯   
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP HOW TO W3.CSS C C++ C# BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS DSA TYPESCRIPT ANGULAR GIT POSTGRESQL MONGODB ASP AI R GO KOTLIN SASS VUE GEN AI SCIPY CYBERSECURITY DATA SCIENCE INTRO TO PROGRAMMING BASH RUST

C++ Tutorial

C++ HOME C++ Intro C++ Get Started C++ Syntax C++ Output C++ Comments C++ Variables C++ User Input C++ Data Types C++ Operators C++ Strings C++ Math C++ Booleans C++ If...Else C++ Switch C++ While Loop C++ For Loop C++ Break/Continue C++ Arrays C++ Structures C++ Enums C++ References C++ Pointers C++ Memory Management

C++ Functions

C++ Functions C++ Function Parameters C++ Function Overloading C++ Scope C++ Recursion C++ Lambda

C++ Classes

C++ OOP C++ Classes/Objects C++ Class Methods C++ Constructors C++ Access Specifiers C++ Encapsulation C++ Inheritance C++ Polymorphism C++ Templates C++ Files C++ Date

C++ Errors

C++ Errors C++ Debugging C++ Exceptions C++ Input Validation

C++ Data Structures

C++ Data Structures & STL C++ Vectors C++ List C++ Stacks C++ Queues C++ Deque C++ Sets C++ Maps C++ Iterators C++ Algorithms

C++ Namespaces

C++ Namespaces

C++ Projects

C++ Projects

C++ How Tos

C++ Add Two Numbers C++ Random Numbers

C++ Reference

C++ Reference C++ Keywords C++ <iostream> C++ <fstream> C++ <cmath> C++ <string> C++ <cstring> C++ <ctime> C++ <vector> C++ <algorithm>

C++ Examples

C++ Examples C++ Real-Life Examples C++ Compiler C++ Exercises C++ Quiz C++ Syllabus C++ Study Plan C++ Certificate


C++ new and delete


The new Keyword

The new keyword lets you manage memory yourself.

In the example below, we create memory space for an integer using new, store the value 35 in it, and print it using a pointer:

Example

int* ptr = new int;
*ptr = 35;
cout << *ptr;
Try it Yourself »

Explanation:

  • new int creates memory space for one integer
  • ptr stores the address of that space
  • *ptr = 35; stores the number 35
  • cout << *ptr; prints the value

So we used new to create memory, and ptr to access it.


The delete Keyword

When you create something with new, it's your job to remove it when you're done.

To do that, use delete:

Example

delete ptr;
Try it Yourself »

This tells C++: "I'm done with this memory, you can clean it up now."

What Happens If You Forget delete?

If you forget to delete memory, your program will still run, but it may use more and more memory over time.

This is called a memory leak, and it can slow down or crash your program over time.


Using new and delete with Arrays

You can also use the new keyword to create dynamic arrays.

Note: For arrays, use new[] and delete[]. For single variables, use new and delete.

Dynamic arrays are useful when you don't know the size of the array in advance - like when the size depends on user input or other values that are not known at the start of the program.

For example, imagine you run a hotel. Since you don't know how many guests will arrive, you ask the user for the number and create that many rooms - one to store each guest's name:

Example

#include <iostream>
#include <string>
using namespace std;

int main() {
  int numGuests;
  cout << "How many guests? ";
  cin >> numGuests;

  // Check for invalid input
  if (numGuests <= 0) {
    cout << "Number of guests must be at least 1.\n";
    return 0;
  }

  // Create memory space for x guests (an array of strings)
  string* guests = new string[numGuests];

  // Enter guest names
  for (int i = 0; i < numGuests; i++) {
    cout << "Enter name for guest " << (i + 1) << ": ";
    cin >> guests[i];
  }

  // Show all guests
  cout << "\nGuests checked in:\n";
  for (int i = 0; i < numGuests; i++) {
    cout << guests[i] << "\n";
  }

  delete[] guests; // Clean up memory
  return 0;
}

Example Result:

How many guests? 3
Enter name for guest 1: John Doe
Enter name for guest 2: Liam Spurs
Enter name for guest 3: Jenny Kasp
Guests checked in:
John Doe
Liam Spurs
Jenny Kasp
Run Example »

When to Use new

In most cases, you don't need to use new. C++ will automatically handle memory for normal variables like:

int age = 35;
string name = "John";

But sometimes, you have to manage memory yourself - especially when:

  • You don't know how much memory you'll need in advance (like how many guests or scores)
  • You want to create memory while the program is running, based on user input
  • You need to store large or flexible amounts of data
  • You want full manual control over memory (e.g., performance-critical code)

In those cases, new helps you create memory, and delete helps you clean it up when you're done.

Tip: If you use new, always remember to use delete (or delete[] for arrays) to avoid memory leaks.



×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
sales@w3schools.com

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
help@w3schools.com

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Copyright 1999-2025 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.