Search code examples
c++membernon-member-functions

Choosing to make a function a member, non-member, private, public, etc


I've searched around for descriptions of the difference between member and non-member functions and, while I'm still quite confused, I thought I'd give an example to clear things up for me a bit. Here's a question from an old test our instructor gave us as study material:

Assume we have a main() program that uses the queue2.h and node2.h template implementations from our text, creating a queue of letters (queue letters).

  1. We want to write a stream operator to insert all characters of a string (thing) into a queue (letters << thing;).

(b) Should we make this << a member or non-member? Private, public, friend, or neither?

  1. We want to provide a tool (call it Get_Front) which returns the head pointer of this queue of characters for future manipulations using the linked list tool kit.
    So, list_head_insert(head_ptr, '2') will place a ‘2’ at the front of my queue when everything is coded properly.

(b) Should we make Get_Front a member or non-member? Private, public, friend, or neither?

I'm guessing the first one should be implemented as a non-member with a friend function, but I'm not sure on the specifics as to why?

Thanks a lot!


Solution

  • (b) Should we make this << a member or non-member? Private, public, friend, or neither?

    Member, public. You create a queue object and overload insertion operator as member function. It can be used to insert characters into the queue.

    Reason: We wanted to insert in queue stream and not in external stream such as cout. It is better practice to use Member functions whenever you can. Friends should be used only when members can't be used.

    Get_Front() becomes a public member function.