Jack F
Jack F

Reputation: 553

Singly linked-list class with constructors

What I want to do is have a singly linked-list class with a default constructor, copy constructor, copy assignment constructer, and destructor. I barely started it because I am confused if a Node with int data and next pointer should be a separate class or the way I did it.

class list {
public:
    list(): next(NULL) {} // default constructor                                   
    list(const list &t){} // copy constructor                                     
    list&   operator= (const list &t) // assignment operator                        
    ~list(){} //destructor                                                        
    void print()    

private:
    struct Node {
        data x;
        Node *next;
    }_list;
}

Upvotes: 1

Views: 3442

Answers (4)

Derek W
Derek W

Reputation: 10026

Having an inner class is fine, however, if/when you implement methods like a constructor for the inner class, then the scope resolution operator needs to include the outer and inner class names. For example,

List::Node::Node(const DataType& nodeData, Node* nextPtr) {stuff}

By declaring the Node class in the private section of the List class you are providing encapsulation against external access, but still letting the List class have access.

Upvotes: 0

Luchian Grigore
Luchian Grigore

Reputation: 258618

Well, logically, a node is a separate structure (class), but in common implementations, the list itself is represented by the first node.

So, basically, you wouldn't have a list class (and if you did, it'd just hold a pointer to the first node + the constructors/assignment operator/destructor):

struct Node {
  data x;
  Node *next;
};

class list{
 public:
  list(): next(NULL) {} // default constructor                                   
  list(const list &t){} // copy constructor                                     
  list& operator= (const list &t) // assignment operator                        
  ~list(){} //destructor                                                        
  void print() ;

 private:
  Node* first;
}

Upvotes: 2

Olaf Dietsche
Olaf Dietsche

Reputation: 74068

This is perfectly valid. If you use Node only in list, it is just an implementation detail. Although, if you need Node outside of list, e.g. in an iterator class, then you need to implement it outside of list.

Upvotes: 0

user1610015
user1610015

Reputation: 6678

If by "separate class" you mean not nested within list, then no, it's better for it to be nested (and private). But that doesn't mean you can't give it constructors, destructors, operators, methods, etc. (i.e. turn it into a full-blown class).

Upvotes: 0

Related Questions