0
0
C++programming~10 mins

Destructor role in C++ - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete 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'
Adelete
BmyClass
CDestructor
DMyClass
Attempts:
3 left
πŸ’‘ Hint
Common Mistakes
Using a different name than the class for the destructor.
Omitting the tilde (~) before the destructor name.
2fill in blank
medium

Complete 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'
ADestructor_called
BDestructor called
C"Destructor called"
Ddestructor
Attempts:
3 left
πŸ’‘ Hint
Common Mistakes
Forgetting the quotes around the message string.
Using a variable name instead of a string literal.
3fill in blank
hard

Fix the error in the destructor declaration.

C++
class MyClass {
public:
    ~MyClass[1];
};
Drag options to blanks, or click blank then click option'
A{}
B()
C;
D[]
Attempts:
3 left
πŸ’‘ Hint
Common Mistakes
Omitting parentheses in the destructor declaration.
Using braces {} instead of parentheses ().
4fill in blank
hard

Fill 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'
Adelete[]
Bnullptr
C0
Ddelete
Attempts:
3 left
πŸ’‘ Hint
Common Mistakes
Using delete instead of delete[] for arrays.
Not setting pointer to nullptr after deletion.
5fill in blank
hard

Fill 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'
Afile
Bfclose
Cnullptr
Dopen
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.