Search code examples
c++linked-listnodes

how do I give the class definition of the following class node here for a llist with and without a friend class?


I am not sure if I am doing this right, but how do I give the class definition of the following class node here for a list with and without a friend class? In which one do I use private: or public:?

Without friend class:

class node { 
public:
    el_t Elm; 
    Node *Next; 
}

With friend class:

class node { 
private:
    el_t Elem; 
    Node* Next;
}

Solution

  • friend is a specifier that grants specific function or the whole class itself access to its protected as well as private members and methods:

    class SomeFriend;
    
    class SomeClass
    {
    public:
        SomeClass(int a, int b, int c) : a_(a), b_(b), c_(c) {}
        virtual ~SomeClass();
    private:
        int a_, b_, c_;
        friend SomeFriend;
    };
    
    class SomeFriend
    {
    public:
        virtual ~SomeFriend();
        int AddABC(SomeClass& b) { return b.a_ + b.b_ + b.c_; }
    };
    

    What is its difference from inheritance, then?

    friend members require an external instance of the base class to access its members, while a derived class is already itself an instance of the base class...

    What else can be improved in the above code?

    You could move the declaration of the class SomeFriend above SomeClass... and just do:

    class SomeClass;
    
    class SomeFriend
    {
    public:
        virtual ~SomeFriend();
        int AddABC(SomeClass& b);
    };
    
    class SomeClass
    {
    public:
        SomeClass(int a, int b, int c) : a_(a), b_(b), c_(c) {}
        virtual ~SomeClass();
    private:
        int a_, b_, c_;
        // Making only the member function 'AddABC' friend of this class...
        friend int SomeFriend::AddABC(SomeClass& b);
    };
    
    int SomeFriend::AddABC(SomeClass& b)
    {
        return b.a_ + b.b_ + b.c_;
    }
    

    Here, you don't make the class the friend, but the specific function that only requires its private and protected members...