Recall that if list is explicitly declared to be of a particular type, for example,
class Box {
private:
int n;
public:
int m;
Box( int a ):n(a) {
// empty constructor
}
int get_n() {
return n;
}
};
If any variable of this type is explicitly declared to be of type Box, its member functions or member variables may be accessed directly using the directly using the . operator:
#include <iostream>
using namespace std;
// Add the Box class here
int main() {
Box box(3);
cout << box.get() << endl;
box.m = 5;
return 0;
}
If, however, the object was dynamically allocated using new and your access to it through a pointer, you must first dereference the pointer:
#include <iostream>
using namespace std;
// Add the Box class here
int main() {
Box *ptr = new Box(3);
cout << (*ptr).get() << endl;
(*ptr).m = 5;
cout << (*ptr).m << endl;
return 0;
}
Due to precedence, it is necessary to wrap the dereferenced pointer in parentheses. This awkward, and consequently, the following short form was introduced:
#include <iostream>
using namespace std;
// Add the Box class here
int main() {
Box *ptr = new Box(3);
cout << ptr->get() << endl;
ptr->m = 5;
cout << ptr->m << endl;
return 0;
}
If the variable is a pointer, use ->, otherwise use ..
If you are using dynamically allocated memory, use ->, otherwise use ..
In Project 1, variables such as list_head, list_tail, and next_node are all addresses, and consequently, to access a member function of the node they are referring to, you must use, for example, list_head->retrieve() or list_head->next_node. In the operator= (assign) function, the argument is passed by reference, and is consequently not a pointer but is a reference to the actual object. For this argument, you must use the . operator, for example, list.head() or list.size().