Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to declare a destructor in a C++ class.
C++
class MyClass { public: ~[1](); };
Drag options to blanks, or click blank then click option'
Attempts:
3 left
π‘ Hint
Common Mistakes
Using a different name than the class for the destructor.
Omitting the tilde (~) before the destructor name.
β Incorrect
The destructor has the same name as the class, preceded by a tilde (~).
2fill in blank
mediumComplete the code to define a destructor that prints a message when called.
C++
MyClass::~MyClass() {
std::cout << [1] << std::endl;
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
π‘ Hint
Common Mistakes
Forgetting the quotes around the message string.
Using a variable name instead of a string literal.
β Incorrect
The message must be a string literal enclosed in double quotes.
3fill in blank
hardFix the error in the destructor declaration.
C++
class MyClass { public: ~MyClass[1]; };
Drag options to blanks, or click blank then click option'
Attempts:
3 left
π‘ Hint
Common Mistakes
Omitting parentheses in the destructor declaration.
Using braces {} instead of parentheses ().
β Incorrect
The destructor declaration must include empty parentheses ().
4fill in blank
hardFill both blanks to complete the destructor definition that frees a dynamically allocated array.
C++
class MyClass { int* data; public: MyClass() { data = new int[10]; } ~MyClass() { [1] data; data = [2]; } };
Drag options to blanks, or click blank then click option'
Attempts:
3 left
π‘ Hint
Common Mistakes
Using delete instead of delete[] for arrays.
Not setting pointer to nullptr after deletion.
β Incorrect
Use delete[] to free arrays and set pointer to nullptr to avoid dangling pointers.
5fill in blank
hardFill all three blanks to complete the destructor that closes a file and resets the pointer.
C++
class FileHandler { FILE* file; public: FileHandler(const char* filename) { file = fopen(filename, "r"); } ~FileHandler() { if ([1] != nullptr) { [2](file); file = [3]; } } };
Drag options to blanks, or click blank then click option'
Attempts:
3 left
π‘ Hint
Common Mistakes
Not checking if file pointer is nullptr before closing.
Using wrong function to close the file.
Not resetting pointer after closing.
β Incorrect
Check if file is not nullptr, then close it with fclose, and reset pointer to nullptr.