A. Destructor has a return type which is not allowed.
B. Destructor name is incorrect; it should be 'destruct'.
C. Constructor is missing a return type.
D. Destructor should be public static.
Solution
Step 1: Check destructor declaration
Destructor must not have a return type. Here, 'void' before '~Sample()' is invalid syntax.
Step 2: Verify other options
Destructor name is correct with '~Sample'. Constructors have no return type but that is correct here. Destructors cannot be static.
Final Answer:
Destructor has a return type which is not allowed. -> Option A
Quick Check:
Destructor = no return type [OK]
Hint: Destructor never has a return type, not even void [OK]
Common Mistakes:
Adding void or other return types to destructor
Misnaming destructor
Making destructor static
5. You have a class Resource that opens a file in its constructor and closes it in its destructor. Which of the following code snippets correctly ensures the file is closed automatically when the object goes out of scope?
hard
A. void useFile() {
Resource* r = new Resource();
// use file
delete r;
} // file closed here automatically
B. void useFile() {
Resource* r = new Resource();
// use file
} // file closed here automatically
C. void useFile() {
Resource r;
// use file
delete &r;
} // file closed here
D. void useFile() {
Resource r;
// use file
} // file closed here automatically
Solution
Step 1: Understand automatic destruction
Objects created on stack (like 'Resource r;') are destroyed automatically when going out of scope, calling destructor to close file.
Step 2: Analyze dynamic allocation
Objects created with 'new' must be deleted manually; otherwise destructor won't run automatically, risking resource leaks.
Final Answer:
void useFile() {
Resource r;
// use file
} // file closed here automatically -> Option D
Quick Check:
Stack objects auto-destroyed, heap objects need delete [OK]
Hint: Use stack objects for automatic destructor calls [OK]
Common Mistakes:
Forgetting to delete heap objects
Trying to delete stack objects
Assuming destructor runs without delete on heap
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.