Question

 

Discuss and implement the destructor for the Book class in C++. When is the destructor called in the lifecycle of a C++ object?

22 Jan 2025
Answer :
Word Count : 340

The destructor in a C++ class is a special member function with the same name as the class preceded by a tilde (`~`). Its primary purpose is to release resources or perform cleanup tasks when an object goes out of scope or is explicitly deleted.

Implementation:  
Suppose we have a `Book` class that dynamically allocates memory to store additional information like book description. The destructor ensures that allocated memory is properly released.

```cpp
#include <iostream>
#include <cstring>

class Book {
private:
    char* description;

public:
    // Constructor
    Book(const char* desc) {
        description = new char[strlen(desc) + 1]; // Allocate memory

______ _______ ___ ________ ____ _____ ______.
__________ ____ _________ ___ __________.
______ ____ ______ __________ ______ ______ ____.
______ ________ _____ ____ __________ _______ ________ ____.
____ ______ _____ _____ _____ _____ ___ ___ _____ _________.
______ ____ _______ ___ ___ ______ _________ _____ ____.
______ _________ _________ __________ ____ ____.
______ ______ _________ _________ _______ _______ ______ _____ ______ _____ _______ _______.
_____ ______ __________ __________ ___ ____.
_______ _________ ___ _____ _____ ____ ___ _________ __________ ______ _________ __________.
_________ __________ _______ _____ ___ ___ _________.
__________ ________ ________ ________ _________ __________ ___ ____.
_________ _______ ______ ____ ______ _________ _________ __________ ____ ___ _________.
__________ _________ _________ _____ ________ _____ _____ _________ _______ _______ _____.
_______ ___ _______ _______ _____ _________ _____.
____ _______ _____ ____ ___ ___ __________ _____.
___ __________ __________ _________ _________ __________.
_______ ____ _________ _______ _______ ____ ____ _____ ______ _________.
_____ _______ ___ ____ ____.
____ _________ ___ _________ _______ ___ __________ ______ _________ ____ ________ _____.
_____ _______ _______ ____ ___ _________.
_____ ______ _____ _______ _______ _____ ___.
___ ___ __________ _____ __________ ________ _____ ______ ___ ___.
____ __________ ______ ___ ________ ________ _____ _______ ____.
__________ ______ _______ ______ _______ ________ ___ _______ ________ ___ ___.
_____ __________ ______ _____ _______ _____ ___ ________ _____ _____ ___.
IGNOU ACADEMY
Your IGNOU journey, made easier.
  • Solved Assignments
  • Study Notes
  • Guess Papers
  • Question Papers
Skip in 10
Top
📞
Call Support Instant phone assistance IGNOU MLIL 6 2025 -  Discuss and implement the destructor for the Book class in C | IGNOU Academy
→
🟢
WhatsApp Chat Fast live messaging
→
Email Us Business enquiries & support
→