I'm new to c++ and tried to get familiar with the language by implementing a LinkedList.
class ListElement {
public:
int val;
ListElement *next;
ListElement(int v, ListElement *n) {val = v; next = n;};
};
ListElement
contains an int value val
and a pointer to the next list element (nullptr
if there is no next element) and a constructor.
class MyLinkedList {
public:
ListElement *head;
MyLinkedList() {head = nullptr;};
ListElement* getHead(void){
return head;
};
void append(int i) {
head = &ListElement(i, head);
};
};
MyLinkedList
contains a pointer to the first element of the list named head
as well as some methods working on the list. Encountering some bugs in those methods I tried to track down their cause. (I'm aware that a getter for a public class member makes no sense at all, originally head
was private.) Doing so I observed the following behaviour I can't explain:
int main() {
MyLinkedList l;
l.append(1);
int x = l.head->val;
cout << "head: " << x << "\n";
int y = l.getHead()->val;
cout << "getHead(): " << y << "\n";
int z = l.head->val;
cout << "head: " << z << "\n";
cin.get();
return 0;
}
Running this code (add #include <iostream>
and using namespace std;
for a working example) prints
head: 1
getHead(): 18085840
head: -858993460
so the first direct access of head
works just as expected, yielding 1
as value of the first list element, but using the getter returns garbage. If head
is then accessed directly again, it also yields garbage, which made me think "Hm, seems like using getHead() somehow garbles the ListMember object", just to discover that
int x = l.head->val;
cout << "head: " << x << "\n";
int z = l.head->val;
cout << "head: " << z << "\n";
prints
head: 1
head: -858993460
without even touching the getter. So is simply accessing l.head
in any way enough to garble it?
No, as
int x = l.head->val;
int z = l.head->val;
cout << "head: " << x << "\n";
cout << "head: " << z << "\n";
returns (as intended) head: 1
two times. So using cout
in between changes my objects or their pointers? And what's wrong with getHead()
as all it does is just return head;
?
So I'm pretty lost here and couldn't find any directly related questions. (This Question has a promising title but doesn't use pointers). Am I totally failing to use pointers in a correct way? Or is some automatic object deletion going on behind the scenes? Or is this just how magiC++ works?