I have done some reading starting on the Rule of three and this has given me some exposure to memory management when writing C++ and it is challenging coming from a Java background.
I'm just writing some toy programs to begin with and just wanting to construct a basic linked list.
I have my Node:
class Node
{
public:
std::string des;
int val;
Node *nxt;
Node();
Node(std::string d, int v) : des(d), val(v);
~Node();
private:
}
And my Linked List:
class LinkedList
{
public:
Node *hd;
Node *tl;
LinkedList() : hd=nullptr, tl=nullptr;
void Append(const Node &nod)
{
hd=nod;
}
~LinkedList();
private:
}
I wanted to write the code like this going from what I have learned so far.
int main(void)
{
std::cout << "Create some objects on the stack." << std::endl;
LinkedList m_ls();
Node m_nod1("first node", 30);
Node m_nod1("second node", 36);
Node m_nod1("third node", 42);
m_ls.Append(m_nod1);
m_ls.Append(m_nod2);
m_ls.Append(m_nod3);
}
I am getting an obvious compiler warning because my assignment of this->hd=nod but it is not obvious to me how I'm to write this properly. Will casting between types and a copy-constructor solve this? Appreciate the help.
&. That should be explained in any introduction to C++ (or C for that matter). This has nothing to do with the copy constructor or casting. However, even with that, passing a pointer/reference to aNodeto the constructor is a fundamentally flawed approach because the List itself should own the Node, so it should be creating it itself as well.Appendfunction instead of "constructor".)Nodeclass as simple as possible. Give it just enough smarts to hold data and know where the next node its Don't give it a destructor. Leave the management of the nodes completely up to theLinkedListand make all of the data observe the Rule of Three. Do not expose theNodeclass to the user. Make it aprivatemember ofLinkedList. If the user can add and removeNodes they create or interact with them, you're allowing the user to shoot themselves in the foot by mixing automatic and dynamic storage or damage theNodeand , by extension, theLinkedList.