Question

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!

Était-ce utile?

La solution 2

(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.

Autres conseils

It is difficult to say not know the true purpose of the program which you have described above. I can give you somewhat of a general answer.

Make a function

  1. PUBLIC if you want it to be accessed by anyone.
  2. PRIVATE if you want only member functions and friends of that class to access.
  3. PROTECTED if you want only member functions and friends of that class as well as member functions and friends of derived class to access.
  4. FRIEND if you want to access the classes private members.

As far as member & non-member is concerned, again it is difficult to say without knowing details about the implementation. If the function has to access private members of the class, it would have to be a member function.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top