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

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++ Type Conversion 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 Mgmt

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++ Destructors C++ The this Pointer C++ Access Specifiers C++ Encapsulation C++ Friend Functions C++ Inheritance C++ Polymorphism C++ Operator Overload C++ Templates

C++ Files

C++ Files

C++ Date

C++ Date

C++ Errors

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

C++ Problem Solving

C++ Problem Solving C++ Build the Logic C++ Test Cases

C++ Data Structures

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

C++ Namespaces

C++ Namespaces

C++ Projects

C++ Projects

C++ Cert

C++ Certificate

C++ How To

C++ How Tos

C++ Examples

C++ Examples C++ Real-Life Examples C++ Compiler C++ Exercises C++ Quiz C++ Code Challenges C++ Practice Problems C++ Syllabus C++ Study Plan

C++ Reference

C++ Reference C++ Keywords C++ <algorithm> C++ <cctype> C++ <cmath> C++ <cstdlib> C++ <cstring> C++ <ctime> C++ <deque> C++ <fstream> C++ <iomanip> C++ <iostream> C++ <list> C++ <map> C++ <memory> C++ <queue> C++ <random> C++ <set> C++ <sstream> C++ <stack> C++ <stdexcept> C++ <string> C++ <unordered_map> C++ <unordered_set> C++ <vector>


C++ Destructors


Share

Destructors

In the Constructors chapter, you learned that a constructor runs automatically when an object is created.

A destructor is the opposite. It is a special method that runs automatically when an object is destroyed.

To create a destructor, use the same name as the class, with a tilde ~ in front of it:

Example

class MyClass {
  public:
    MyClass() {   // Constructor
      cout << "Object created\n";
    }
    ~MyClass() {  // Destructor
      cout << "Object destroyed\n";
    }
};

int main() {
  MyClass myObj;
  cout << "Hello World!\n";
  return 0;
}

Try it Yourself »

The object is created when MyClass myObj; runs, and destroyed when main() ends. That is why "Object destroyed" is printed last.

Destructor Rules

  • The destructor has the same name as the class, with a ~ in front.
  • It has no return type and no parameters.
  • A class can only have one destructor.
  • It is automatically called when the object is destroyed. You do not call it yourself.

When Is a Destructor Called?

An object is destroyed when it goes out of scope. For example, an object that is created inside a function is destroyed when the function ends:

Example

class Car {
  public:
    Car() {
      cout << "Car created\n";
    }
    ~Car() {
      cout << "Car destroyed\n";
    }
};

void drive() {
  Car myCar;
  cout << "Driving...\n";
}  // myCar is destroyed here

int main() {
  drive();
  cout << "Back home\n";
  return 0;
}

Try it Yourself »

myCar only lives inside drive(). So "Car destroyed" is printed when drive() ends, before "Back home".

An object that is created with new is destroyed when you use delete on it.



Why Use a Destructor?

A destructor is the place to clean up after an object. The most common job is to free memory that the object created with new.

In the new and delete chapter, you created a list of hotel guests with new, and had to remember to free it with delete[]. If the class does this in its destructor, the memory is always freed, and you cannot forget it:

Example

class Hotel {
  public:
    string* guests;

    Hotel(int rooms) {
      guests = new string[rooms];  // Get memory
      cout << "Rooms ready\n";
    }

    ~Hotel() {
      delete[] guests;  // Free the memory
      cout << "Memory freed\n";
    }
};

int main() {
  Hotel myHotel(3);
  myHotel.guests[0] = "Liam";
  cout << "Guest: " << myHotel.guests[0] << "\n";
  return 0;
}

Try it Yourself »

The constructor gets the memory, and the destructor gives it back. You never call delete[] in main().




Free account

Track your progress

XP earned 0 Day streak 0 Spaces 0 League —

New

Learn in Adventure Mode W3Schools Adventure App

Coding fundamentals as bite-sized lessons and challenges.

×

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, cookies and privacy policy.

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