When the constructor is called with the el, head parameters, does the value of head not get initialised to 0 in the definition of the IntNode constructor. |
It's easiest for me to explain this by example.
1 2 3
|
head = 0;
head = new IntNode(1,head); // node1
head = new IntNode(2,head); // node2
|
Here, the following things happen:
line 1:
- head is null (0)
line 2:
- new node is created (node1).
- node1->next is set to 'head', since 'head' is null, this means node1->next is also null
- head now points to node1
line 3:
- new node created (node2)
- node2->next is set to 'head'. 'head' points to node1, so node2->next also points to node1
- head now points to node2
so we're left with:
head = &node2
node2->next = &node1
node1->next = null
What is the purpose of the const after the declaration? |
It marks the function as a const member function, meaning you can call it with a const object:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
|
class Foo
{
public:
void f_const() const {}
void f_nonconst() { }
};
int main()
{
const Foo c; // const object
Foo nc; // nonconst object
nc.f_const(); // OK
nc.f_nonconst(); // OK
c.f_const(); // OK
c.f_nonconst(); // ERROR, a const object can't call a non-const function
|
The reason that isn't allowed is because const objects are "guaranteed" that you won't change them, but a non-const function might change the state of the object. So by designating the function as const, you are saying "it is guaranteed that this function does not change the state of the object), thereby making it OK to call that function with const objects.