user2794944
user2794944

Reputation: 11

C++ Access struct in sourcefile

I've defined my struct in a .h file, and I'm trying to access it from a .cc file. However, I keep getting errors when compiling.

This is in my .h:

class List
{ 
 public:
   struct ListNode 
   {
     string data;
     ListNode* next;
   };
}

And this is in my .cc file: (the .h file is included)

struct ListNode* startPtr;

List::List(void)
{
  startPtr = new ListNode;
  startPtr = nullptr;
}

When trying to use it like this,

void Print()
 { 
 while (startPtr) 
  { 
    cout << startPtr->data << endl;
    startPtr = startPtr->next; 
  }
 }

I get errors like

Forward declaration and unauthorized usage of undefined type. 

Upvotes: 1

Views: 91

Answers (5)

KKas
KKas

Reputation: 5

Let me rephrase the answer of Kiril Kirov. You have 2 types in your program: - ListNode defined in the scope of the class List - ListNode defined in global scope The 2nd one is defined using forward declaration, without actual description of its content. That's your compiler trying to say to you. To fix the error you need to refer correct ListNode type, when defining startPtr, e.g. you should write:

List::ListNode* startPtr;

instead of

struct ListNode* startPtr;

Upvotes: 0

Kiril Kirov
Kiril Kirov

Reputation: 38163

You must include the .h file in your .cc file AND as ListNode is defined inside class List, if you want to access it from outside the class (outside its definition & its methods), you need to specify the scope like this List::ListNode.

Note, that if class List is defined inside a specific namespace, for example my_namespace, if you want to access ListNode from the global namespace, you need to specify this, too. Like: my_namespace::List::ListNode.

Upvotes: 3

4pie0
4pie0

Reputation: 29724

  • include the .h file in your .cc file
  • refer to structure as List::ListNode as it is a nested type
  • don't have to write struct ListNode* startPtr; just List::ListNode* startPtr;
  • insert semicolon after class List definition in .h file

Upvotes: 0

Sebastian Redl
Sebastian Redl

Reputation: 71959

You made ListNode a nested type of List, so you have to refer to it as List::ListNode. You can leave off the struct when you declare startPtr though.

Of course, since List::ListNode is redundant, you might want to rename it to just Node.

Upvotes: 0

Ivaylo Strandjev
Ivaylo Strandjev

Reputation: 70929

Your list node class is inner class. It's type is: List::ListNode not just ListNode like you use it.

Also as you mention forward declaration(though I don't see any in this code): you will not be able to forward declare an inner class.

Upvotes: 0

Related Questions