Home > OS >  Friend class in C not allowing access to private member attributes
Friend class in C not allowing access to private member attributes

Time:11-20

I recently started C and to be completely honest my lecturer isn't much help, I am trying to give a linked list friend access to a node class. From what I can see I have declared everything I need, but I still cant access the Node private members , if somebody could see something im missing that would be great!

My node header file:

```#ifndef NodeofBook_h
#define NodeofBook_h

#include <stdio.h>
#include "Book.h"

class ListOfBooks;
//
class NodeofBook {
    
    friend class ListOfBooks;
    
private:
    NodeofBook* next;
    Book* theBook;
    
public:
    
};


#endif /* NodeofBook_h */

My linked list header file :

#ifndef ListOfBooks_h
#define ListOfBooks_h

#include <stdio.h>
#include "NodeofBook.h"

class ListOfBooks {
    
private:
    
public:
    ListOfBooks();
    void insertBack(int);
    void displayList();
    int deleteMostRecent();
    int deleteInt(int pos);
};


#endif /* ListOfBooks_h */

My Linked List cpp file:

#include "ListOfBooks.h"

int ListOfBooks(){
    
    return 0;
}

ListOfBooks::ListOfBooks(){
    theBook->title = "noTitleYet";
    theBook->isbn = 0000;
    next = NULL;
}

I am getting an error stating Use of undeclared identifier 'theBook'

Any help is really appreciated!

CodePudding user response:

NodeofBook declaring that ListofBooks is a friend class just means that the implementation of ListofBooks can access NodeofBook's private members, but there still needs to be an instance of NodeofBook to access. Its members are not static; non-static member variables are part of some object. That is, just because the ListofBooks is a friend of NodeofBook does not mean that it magically has instances of NodeofBookmembers.

A friend relationship is not an is-a relationship like inheritance: it is just about access.

  • Related