Home > Enterprise >  Private Struct only returnable with private listed first in a class
Private Struct only returnable with private listed first in a class

Time:04-13

So I have run into the case where returning an object of type Node is not allowed if the private variables have been listed after the public as can be seen by the two screenshots below. There CLion is giving me an error as can be seen with Node being red. I understand why this is, however I am wondering if there is anyway to fix this issue without placing/declaring private before public?

Public before private (Desired): enter image description here

Private before public (what works): enter image description here

Thanks!

CodePudding user response:

The problem is that when the return type Node* is encountered in the member function getCurrentPalyer definition, the compiler doesn't know that there is a struct named Node. So you've to tell that to the compiler which you can do by adding a forward declaration for Node as shown below:

class Palyer 
{ private: struct Node;    //forward declaration added for Node
  public:
    
    Node* func()
    {
        return head;
    }
  private:
    struct Node {};
    Node* head;
};

Working Demo

  •  Tags:  
  • c
  • Related