WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

C++ · Basic · question 7 of 100

What is a destructor, and when is it called in the lifecycle of a C++ object?

📕 Buy this interview preparation book: 100 C++ questions & answers — PDF + EPUB for $5

A destructor is a special member function in C++ that is called when an object of a class is destroyed or deleted. Its purpose is to perform any necessary cleanup operations, such as freeing memory, releasing resources, or closing files, before the object is removed from memory.

In C++, a class can have one destructor, which has the same name as the class but is preceded by a tilde ( ) character. The destructor is automatically called when an object of the class is destroyed or deleted, either explicitly using the delete operator or when it goes out of scope.

The destructor is typically used to perform cleanup operations that are necessary to release resources or memory that was allocated by the object during its lifetime. For example, if an object allocates memory using the new operator, the destructor should release that memory using the delete operator to prevent memory leaks.

Here’s an example of a class with a destructor that releases memory:

    class MyObject {
        public:
        MyObject() {
            myData = new int[10];
            std::cout << "Constructor called" << std::endl;
        }
        
        ~MyObject() {
            delete[] myData;
            std::cout << "Destructor called" << std::endl;
        }
        
        private:
        int* myData;
    };
    
    int main() {
        MyObject myObject; // Constructor called
        // do something with myObject
        // ...
        return 0; // Destructor called
    }

In this example, the constructor allocates an array of integers using the new operator, and the destructor releases that memory using the delete[] operator. When the object goes out of scope at the end of the main() function, the destructor is automatically called and the memory is released.

In summary, a destructor is a special member function in C++ that is called when an object of a class is destroyed or deleted. Its purpose is to perform any necessary cleanup operations, such as freeing memory, releasing resources, or closing files, before the object is removed from memory. The destructor is automatically called when the object goes out of scope or is explicitly deleted using the delete operator.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic C++ interview — then scores it.
📞 Practice C++ — free 15 min
📕 Buy this interview preparation book: 100 C++ questions & answers — PDF + EPUB for $5

All 100 C++ questions · All topics