c++ - Should I initialize a struct's variables within the constructor of its containing class? -


i have header file class called 'list' , struct called 'node' within private part of class. together, class , struct make doubly threaded linked list of winery objects (winery being it's own class). i'm wondering if best implement , de-implement node struct's variables within list constructor , deconstructor (like example, throws errors in compiler):

list::list() {     struct node     {         item = winery::winery()         nextbyname = nullptr;         nextbyrating = nullptr;     };     headbyname = nullptr;     headbyrating = nullptr; } list::~list() {     struct node     {         delete item;         delete nextbyname;         delete nextbyrating;     };     delete headbyname;     delete headbyrating; } 

my compiler throws error when delete nodes within list constructor , deconstructor; example above incorrect in ways. still seems me solution work without methodology, not exact code.

i'm curious if better implement , de-implement struct separately (like this):

list::node::node() {     item = winery::winery()     nextbyname = nullptr;     nextbyrating = nullptr; } list::node::~node() {     delete item;     delete nextbyname;     delete nextbyrating; } 

when delete elements separately (above), constructor throws error delete item;. know why is? can explain why don't need delete winery item? should call winery deconstructor there?

should entirely different? i've looked online, , in textbooks, there no clear answer on this. appreciate guys help, , if explain why solution best (if best), extremely grateful. started learning c++ few months ago after all.

by way, list.h file looks like:

#include "winery.h"  class list { public:     list();     ~list();     void addwinery();     void removewinery();     void displaybyrating() const;     void displaybyname() const;     void searchbyname() const; private:     struct node     {         winery item;         node * nextbyname;         node * nextbyrating;     };      node * headbyname;     node * headbyrating; };  

to initialize, this:

class list { public:     list();     // etc. private:     struct node     {         winery item;         node * nextbyname = nullptr;         node * nextbyrating = nullptr;     };      node * headbyname = nullptr;     node * headbyrating = nullptr; };  

and not need constructor take further action.

your destructor suspicious though. if each node * supposed own object pointing to, use std::unique_ptr<node> instead of node *. , if isn't delete not right solution.


Comments