[TriLUG] OT: C++ question, linked list of objects
Tanner Lovelace
clubjuggler at gmail.com
Sun Apr 2 21:34:32 EDT 2006
On 4/2/06, Joseph Mack NA3T <jmack at wm7d.net> wrote:
> This is part of homework for a course I'm doing. I'm
> required to make a linked list of objects. I can do a linked
> list of structs, but when I do it with objects, object->next
> is private, which makes me think that I'm on the wrong
> track. Part of the homework is figuring out how to have a
> class as a node in a linked list.
What class at what university?
> Google gives me stl libraries in template format, which I
> don't understand. I looked at newsgroups - it seemed to be
Of course it would give you Standard Template Library (STL)
stuff in template format. It's right in the name!
> either off-topic or I didn't understand it. All the webpages
> I've looked at have structs as the nodes in a linked list.
structs and classes in C++ are exactly the same thing with
only one difference. structs default to public access while
classes default to private access.
> (Why we have to figure this out ourselves, rather than being
> given some guidance in lectures and then go off and
> implement it is another matter.)
If you have to do it yourself, why are you asking here?
> I'm new at C++, can't do templates etc, so the explanation
> will have to be at a simple level.
>
> Here's the object class
>
> //Submarine.h
> class Submarine {
>
> private:
> int num_engines;
> //long list of private attributes
> .
> .
> Submarine* next;
>
> public:
> };
>
Try adding getters and setters?
Or, more simply put, add a method (or in other words,
a function in the class) that takes a
pointer to a Submarine and sets next to that
value. Call it setNext or something. :-P
Also add a method that returns the value of next.
Call it getNext() or something. :-P That's what
getters and setters are.
>
> Here's the list class
>
> //List.h
> class List{
>
> private:
> Submarine* head;
> Submarine* tail;
> int count; //number of submarines
> ???
>
> What should go in the "???" so that I can do something like
>
> public:
>
> void insert(const Submarine& submarine){
> .
> .
> Submarine* current;
> submarine.next = current; //problem: next is private,
> //can use accessors but seems clunky
> .
Why does it "seem clunky"? By using accessors, you can
change the underlying implementation without having the list
class change. That doesn't seem clunky to me.
> }
>
> }; //List class
>
> Am I supposed to use accessors or have I got the design
> completely wrong?
Yes, you should use accessors, also known as
getters and setters.
Cheers,
Tanner
--
Tanner Lovelace
clubjuggler at gmail dot com
http://wtl.wayfarer.org/
(fieldless) In fess two roundels in pale, a billet fesswise and an
increscent, all sable.
More information about the TriLUG
mailing list