I am currently on chapter 17 of "Programming: Principles and Practice using C++", and I came across a code on doubly-linked list. Questions have been asked on this set of codes before for (e.g. Member access in a doubly-linked list), however I have a question that wasn't asked/answered.
The code basically arranges "Freya" as a predecessor of "Odin", and makes "Odin" a predecessor of "Thor", and the other way round as successors. The code is as follows:
struct Link {
string value;
Link* prev;
Link* succ;
Link(const string& v, Link* p = nullptr, Link* s = nullptr)
: value(v), prev(p), succ(s) {}
};
int main()
{
Link* norse_gods = new Link{ "Thor", nullptr, nullptr };
norse_gods = new Link{ "Odin", nullptr, norse_gods };
norse_gods->succ->prev = norse_gods;
norse_gods = new Link{ "Freya", nullptr, norse_gods };
norse_gods->succ->prev = norse_gods;
}
What I would like to know is that why the code:
norse_gods = new Link{ "Odin", nullptr, norse_gods }
is able to point to the old address: new Link{ "Thor", nullptr, nullptr }
, and making Thor the successor of Odin since norse_god
should already be pointing to the new address: new Link{ "Odin", nullptr, norse_gods }
? Is there some order or evaluation or concept that I am missing out?
The evaluation is first done on the right side and then operator=
kicks in and does the assignment. This is caused by the priority of operator=
. See C++ Operator Precedence.
At the first line of main
, you are creating a Link
with name "Thor" and pointing norse_gods
to it.
At the second line, you are creating a Link
with name "Odin" and a successor norse_god
, which is still pointing at Thor at the moment of construction.
After that, norse_gods
is updated to point to "Odin".
This behavior is normal for C-like languages.