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.
To answer your specific question - to fix the compiler error, you would need to drop the
constfrom yournodparameter, and then use the address-ofoperator&to get the memory address of the passedNodeobject when assigning it to thehdpointer, eg:However, this is not the correct way to write a linked list class (at least in this example). You should instead not let the user pass in
Nodeobjects at all, they should only pass in the data they want to add to the list, let theLinkedListclass handle theNodeobjects internally as needed.For example: