I was working on a homework assignment and I stumbled upon a roadblock
I created a linked list class that looks something like this
List.h
class List{
struct Node{
string data
etc...
}
public:
Node* lastNode(Node* root);
List.cpp
#include "List.h"
List::Node* lastNode(Node* root){
while(root && root->next){
root = root->next;
}
return root;
}
When I try to run the code, it says "struct List::Node is private" within this context (starting with the function header for lastNode in List.cpp)
I'm not understand what's causing this. I know that private fields can only be accessed by member functions of the same class, but isn't lastNode a member function?
defines a global function named
lastNodereturning aList::Node*. You wanted to define this as a member function ofList. To do this, you simply qualify the namelastNodewithList::.The second
List::, on the function name, declares that this function "belong"s toList, so the secondNode, which comes after it, does not need to be qualified byList::again. The return type, since it comes before theList::on the last node, is still interpreted in global scope, and so you need to qualify it. I don't think there's any good reason for this except historical inertia, a holdover from when compilers were dumb enough to get confused by this. You can also place the return type after the qualified function name, where you can leave off the qualifier:Godbolt