Basically I encountered a few problems when I was fiddling with designing a basic singly linked list. Here are the declarations
struct Node {
int val;
Node* next;
};
struct SinglyLinkedlist {
int size;
Node* head;
SinglyLinkedlist();
const Node* Begin() const {
printf("const begin\n");
if (size > 0)
return head->next;
}
Node* Begin() {
printf("begin\n");
if (size > 0)
return head->next;
}
};
I've seen in STL containers, e.g std::queue, that functions with the same name could co-exist like this,
//std::queue
value_type& front();
const value_type& front() const;
it caught me by surprise because it didn't trigger compilation failure like function redefinition e.g functions with the same name, nor did it form a function overloading, e.g function with same names but with different argument types. Therefore, I was wondering if this is a kind of function overloading I didn't know of or some other sorts? and how does the program know which Begin() to call during run-time, I am guessing the compiler would detect the CONSTNESS in the context and decide which to call? The other problem I was having was that without explicitly overloading * operator, *Begin() e.g Node* is dereferenced and print out the val value, basically the same as Begin()->val, I wonder if * operator should function this way.Thank you very much.
int main()
{
SinglyLinkedlist l;
l.Push(1);
l.Push(2);
l.Push(3);
l.PrintList();
printf("%d\n",*l.Begin()); //print out 1 same as l.Begin()->val
}