This might seem like a silly question to the more seasoned C++ coders out there, but I thought once you have a class and you create an object of that class, you call a public method of that class using the object you created (unless it is a static method, in which case you call it either using an object or the class name itself)?
Then why does this work?
Function definition:
template <typename Object>
void printList(const List<Object>& theList) {
if (theList.isEmpty())
cout << "Empty list!" << endl;
else {
ListItr<Object> itr = theList.first();
for(; !itr.isPastEnd(); itr.advance())
cout << itr.retrieve() << " ";
}
cout << endl;
}
Function call:
printList(myList);
What am I missing here? How does the rest of the program know that printList()
belongs to the class List<int>
unless I call printList()
using an object of List<int>
?
This works too by the way, I just checked. I would have used this way of calling and defining the function. Note that this time the function is defined using the this
pointer, the way I would have thought it works.
Function definition:
template <typename Object>
void List<Object>::printList() {
if(this->isEmpty())
cout << "Empty list!" << endl;
else {
ListItr<Object> itr = this->first();
for(; !itr.isPastEnd(); itr.advance())
cout << itr.retrieve() << " ";
}
cout << endl;
}
Function call:
myList.printList();