What is a destructor in C ?
The destructor in C is a special member function that is automatically called when an object is out of scope or is explicitly deleted. Its main purpose is to clean up resources that an object may acquire during its life cycle, such as memory, file handles, or network connections. The destructor is automatically called in the following cases: when a local variable leaves scope, when a delete is called on the pointer, and when an external object containing the object is destructed. When defining the destructor, you need to add ~ before the class name, and there are no parameters and return values. If undefined, the compiler generates a default destructor, but does not handle dynamic memory releases. Notes include: Each class can only have one destructor and does not support overloading; it is recommended to set the destructor of the inherited class to virtual; the destructor of the derived class is executed first, and then the base class destructor is automatically called. When deleting derived class objects using base class pointers, the base class destructor must be virtual, otherwise the behavior is undefined. Although modern C recommends using smart pointers and RAII patterns, it is still important to understand the working mechanism of destructors, especially when dealing with legacy code or performance-sensitive systems.

A destructor in C is a special member function that gets called automatically when an object goes out of scope or is explicitly deleted. Its main job is to clean up resources that the object might have acquired during its lifetime — like memory, file handles, or network connections.

When Is a Destructor Called?
Destructors run automatically under certain conditions:
- When a local (automatic) variable goes out of scope
- When
deleteis called on a pointer to an object - When an object is part of another object (like a member variable), and the outer object's destructor runs
You don't need to call it manually unless you're managing raw points and using dynamic memory allocation.

Examples include:
- A class that opens a file in its constructor should close it in the destructor.
- An object that allocates memory with
newshould free it withdelete.
How to Define a Destructor
You define a destructor by putting a tilde ~ before the class name, and it takes no arguments and returns nothing:

class MyClass {
public:
~MyClass() {
// Cleanup code here
}
};If you don't define one, the compiler will generate a default destructor for you — but it won't handle custom cleanup like freeing dynamically allocated memory.
Some things to keep in mind:
- You can only have one destructor per class — no overloading
- It's good practice to make destructors virtual if your class is meant to be inherited from
Destructors and Inheritance
When dealing with derived classes:
- The destructor of the derived class runs first
- Then the base class destructor is called automatically
This ensures that anything set up by the base class is safely cleaned up after the derived class is done.
If you're deleting a derived class object through a base class pointer, always declare the base class destructor as virtual . Otherwise, the behavior is undefined.
So instead of this:
class Base {};Do this:
class Base {
public:
virtual ~Base() {}
};This small details helps prevent resource leaks in polymorphic types.
Final Notes
Destructors are cruel for proper resource management in C . While modern C encourages the use of smart points and RAII (Resource Acquisition Is Initialization), understanding how destructors work is still essential, especially when working with legacy code or performance-critical systems.
They aren't complicated, but they do require careful handling — especially when manual memory management is involved.
Basically that's it.
The above is the detailed content of What is a destructor in C ?. For more information, please follow other related articles on the PHP Chinese website!
Hot AI Tools
Undress AI Tool
Undress images for free
Undresser.AI Undress
AI-powered app for creating realistic nude photos
AI Clothes Remover
Online AI tool for removing clothes from photos.
Clothoff.io
AI clothes remover
Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!
Hot Article
Hot Tools
Notepad++7.3.1
Easy-to-use and free code editor
SublimeText3 Chinese version
Chinese version, very easy to use
Zend Studio 13.0.1
Powerful PHP integrated development environment
Dreamweaver CS6
Visual web development tools
SublimeText3 Mac version
God-level code editing software (SublimeText3)
How to fix missing MSVCP71.dll in your computer? There are only three methods required
Aug 14, 2025 pm 08:03 PM
The computer prompts "MsVCP71.dll is missing from the computer", which is usually because the system lacks critical running components, which causes the software to not load normally. This article will deeply analyze the functions of the file and the root cause of the error, and provide three efficient solutions to help you quickly restore the program to run. 1. What is MSVCP71.dll? MSVCP71.dll belongs to the core runtime library file of Microsoft VisualC 2003 and belongs to the dynamic link library (DLL) type. It is mainly used to support programs written in C to call standard functions, STL templates and basic data processing modules. Many applications and classic games developed in the early 2000s rely on this file to run. Once the file is missing or corrupted,
C operator overloading example
Aug 15, 2025 am 10:18 AM
Operator overloading in C allows new behaviors of standard operators to be assigned to custom types, 1. Return new objects through member function overloading; 2. Overload = Modify the current object and return reference; 3. Friend function overloading
C vector of strings example
Aug 21, 2025 am 04:02 AM
The basic usage of std::vector includes: 1. Declare vector; 2. Add elements with push_back(); 3. Initialize with initialization list; 4. Loop traversal with range for; 5. Access elements through index or back(); 6. Direct assignment of values to modify elements; 7. Delete the end elements with pop_back(); 8. Call size() to get the number of elements; it is recommended to use constauto& to avoid copying, pre-allocate reserve() to improve performance, and pay attention to checking that it is not empty before access. This data structure is an efficient and preferred way to handle string lists.
C false sharing example
Aug 16, 2025 am 10:42 AM
Falsesharing occurs when multiple threads modify different variables in the same cache line, resulting in cache failure and performance degradation; 1. Use structure fill to make each variable exclusively occupy one cache line; 2. Use alignas or std::hardware_destructive_interference_size for memory alignment; 3. Use thread-local variables to finally merge the results, thereby avoiding pseudo-sharing and improving the performance of multi-threaded programs.
How to write a simple TCP client/server in C
Aug 17, 2025 am 01:50 AM
The answer is that writing a simple TCP client and server requires the socket programming interface provided by the operating system. The server completes communication by creating sockets, binding addresses, listening to ports, accepting connections, and sending and receiving data. The client realizes interaction by creating sockets, connecting to servers, sending requests, and receiving responses. The sample code shows the basic implementation of using the Berkeley socket API on Linux or macOS, including the necessary header files, port settings, error handling and resource release. After compilation, run the server first and then run the client to achieve two-way communication. The Windows platform needs to initialize the Winsock library. This example is a blocking I/O model, suitable for learning basic socket programming.
How to write a basic Makefile for a C project?
Aug 15, 2025 am 11:17 AM
AbasicMakefileautomatesC compilationbydefiningruleswithtargets,dependencies,andcommands.2.KeycomponentsincludevariableslikeCXX,CXXFLAGS,TARGET,SRCS,andOBJStosimplifyconfiguration.3.Apatternrule(%.o:%.cpp)compilessourcefilesintoobjectfilesusing$
How to link libraries in C
Aug 21, 2025 am 08:33 AM
To link libraries in C, you need to use -L to specify the library path when compiling, -l to specify the library name, and use -I to include the header file path to ensure that the static or dynamic library files exist and are named correctly. If necessary, embed the runtime library path through -Wl,-rpath, so that the compiler can find the declaration, the linker can find the implementation, and the program can be successfully built and run.
How to configure IntelliSense for C in VSCode
Aug 16, 2025 am 09:46 AM
To correctly configure IntelliSense for C in VSCode, first install Microsoft's C/C extension, then set the compiler path, include directories and C standards. You can manually configure the build information by editing c_cpp_properties.json or automatically obtain the build information using compile_commands.json. Finally, restart and verify that the IntelliSense function is working properly, ensuring that code completion, syntax highlighting and error detection are accurate.


