0
0
C++programming~5 mins

Destructor role in C++ - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is the main purpose of a destructor in C++?
A destructor is a special member function that is called automatically when an object goes out of scope or is deleted. Its main purpose is to release resources and perform cleanup tasks like freeing memory or closing files.
Click to reveal answer
beginner
How do you declare a destructor in a C++ class?
A destructor is declared with a tilde (~) followed by the class name, and it has no return type or parameters. For example: <br> <code>~ClassName() { /* cleanup code */ }</code>
Click to reveal answer
beginner
When exactly is a destructor called?
A destructor is called automatically when an object is destroyed, which happens when:<br>1. A local object goes out of scope.<br>2. A dynamically allocated object is deleted.<br>3. A program ends and global/static objects are cleaned up.
Click to reveal answer
intermediate
Can you call a destructor explicitly in C++? Should you?
You can call a destructor explicitly, but it is not recommended because it can cause undefined behavior if the object is destroyed again automatically. It's best to let C++ handle destructor calls.
Click to reveal answer
intermediate
Why is it important to define a destructor when your class manages dynamic memory?
If your class allocates memory dynamically (e.g., with new), you must define a destructor to free that memory (e.g., with delete). Otherwise, your program will leak memory, which wastes resources and can cause crashes.
Click to reveal answer
What symbol is used to declare a destructor in C++?
A# (hash)
B* (asterisk)
C& (ampersand)
D~ (tilde)
When is a destructor automatically called?
AWhen a variable is declared
BWhen a function is called
CWhen an object goes out of scope or is deleted
DWhen a program starts
What happens if you forget to define a destructor for a class that uses dynamic memory?
AMemory leaks can occur
BThe program runs faster
CThe compiler adds a destructor automatically that frees memory
DNothing happens
Can a destructor have parameters or return a value?
ADestructors can have parameters but no return type
BNo, destructors have no parameters and no return type
CYes, destructors return an int
DYes, destructors can have parameters
Is it good practice to call a destructor explicitly?
ANo, it can cause problems and should be avoided
BYes, always call destructors explicitly
COnly if the destructor is public
DOnly for static objects
Explain the role of a destructor in a C++ class and when it is called.
Think about what happens when an object is no longer needed.
You got /4 concepts.
    Why must you define a destructor if your class uses dynamic memory allocation?
    Consider what happens if memory is not freed.
    You got /3 concepts.