I've recently returned to C++ after a break of a few years and would like a few points clarifying about new and delete, as used in class constructors / destructors.
I understand that every single thing created using new, must be explicitly deleted before the program quits. Correct?
Following Qt's built in Address Book tutorials (as sadly all the tuxradar ones fail with segmentation faults) I note that even though the class constructor in question uses new to create dynamic objects, the destructor is left empty. Ok, that might be down to stripping down the code for the purposes of education but when I add delete commands to the destructor for each instance of new in the constructor, I run into trouble. See the annotations in the code.
- Code: Select all
QLabel *nameLabel = new QLabel(tr("Name"));
nameLine = new QLineEdit; // nameLine declared as (private) pointer in class header file
QLabel *addressLabel = new QLabel(tr("Address"));
addressText = new QTextEdit; // addressText declared as (private) pointer in class header file
QGridLayout *mainLayout = new QGridLayout;
setWindowTitle(tr("Simple Address Book"));
// delete nameLabel; // <-- Compiler error: Out of scope
delete nameLine; // declared as private pointer in class header file
// delete addressLabel; // <-- Compiler error: Out of scope
delete addressText; // declared as private pointer in class header file
// delete mainLayout; // <-- Compiler error: Out of scope
Is there a memory leak if delete is not called for these objects, and if so, how to delete the ones that are declared out of scope in the destructor?