Discuss and implement the destructor for the Book class in C++. When is the destructor called in the lifecycle of a C++ object?
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
__________ ____ _________ ___ __________.
______ ____ ______ __________ ______ ______ ____.
______ ________ _____ ____ __________ _______ ________ ____.
____ ______ _____ _____ _____ _____ ___ ___ _____ _________.
______ ____ _______ ___ ___ ______ _________ _____ ____.
______ _________ _________ __________ ____ ____.
______ ______ _________ _________ _______ _______ ______ _____ ______ _____ _______ _______.
_____ ______ __________ __________ ___ ____.
_______ _________ ___ _____ _____ ____ ___ _________ __________ ______ _________ __________.
_________ __________ _______ _____ ___ ___ _________.
__________ ________ ________ ________ _________ __________ ___ ____.
_________ _______ ______ ____ ______ _________ _________ __________ ____ ___ _________.
__________ _________ _________ _____ ________ _____ _____ _________ _______ _______ _____.
_______ ___ _______ _______ _____ _________ _____.
____ _______ _____ ____ ___ ___ __________ _____.
___ __________ __________ _________ _________ __________.
_______ ____ _________ _______ _______ ____ ____ _____ ______ _________.
_____ _______ ___ ____ ____.
____ _________ ___ _________ _______ ___ __________ ______ _________ ____ ________ _____.
_____ _______ _______ ____ ___ _________.
_____ ______ _____ _______ _______ _____ ___.
___ ___ __________ _____ __________ ________ _____ ______ ___ ___.
____ __________ ______ ___ ________ ________ _____ _______ ____.
__________ ______ _______ ______ _______ ________ ___ _______ ________ ___ ___.
_____ __________ ______ _____ _______ _____ ___ ________ _____ _____ ___.
- Solved Assignments
- Study Notes
- Guess Papers
- Question Papers
✓ Unlock up to 60% of the answer
✓ No payment required