1

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?

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
AlexDong11
  • 11
  • 1

1 Answers1

0
List::Node* lastNode(Node* root) { ... }

defines a global function named lastNode returning a List::Node*. You wanted to define this as a member function of List. To do this, you simply qualify the name lastNode with List::.

List::Node *List::lastNode(Node *root) { ... } // * placement is more idiomatic this way

The second List::, on the function name, declares that this function "belong"s to List, so the second Node, which comes after it, does not need to be qualified by List:: again. The return type, since it comes before the List:: 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:

auto List::lastNode(Node *root) -> Node* { ... }

Godbolt

HTNW
  • 27,182
  • 1
  • 32
  • 60