user379888
user379888

Reputation:

Linked List implementation with structures or class?

I am starting data structures in C++ and while reading, I came up to the following snippet,

template <class Node_entry>
struct Node {
// data members
Node_entry entry;
Node<Node_entry> *next;
// constructors
Node( );
Node(Node_entry, Node<Node_entry> *link = NULL);
};

Can anyone please elaborate why the author choose a structure and not a class for the implementation of the singly linked list? Thanks.

Upvotes: 2

Views: 3461

Answers (7)

Jaswanth Alla
Jaswanth Alla

Reputation: 1

If you are doing it from algorithms and data structures point of view anything is fine but when it comes to production members of a struct are public so visible to everything outside but classes are by default private

Upvotes: 0

john
john

Reputation: 87959

Probably because s/he wanted to teach algorithms and data structures, and didn't want to distract with OO design issues.

Upvotes: 0

K&#39;&#39;
K&#39;&#39;

Reputation: 5228

From algorithms and data structures point of view, there is no difference between doing it using structure or classes! Books that are talking about algorithms or data structure don't care about OOP, for example, in Introduction to Algorithms they are using pascal and sometimes pseudo code. The important thing is to deliver the idea. The author may choose to use structures because he doesn't want to bother the reader about OOP principles and best practices, he doesn't want you to say hey why he defined this field public and not private with setters and getters. by this way you are getting far from data structure and algorithms.

Upvotes: 1

Nemanja Trifunovic
Nemanja Trifunovic

Reputation: 24551

He wanted the default access to be public - that's the only difference between classes and structures in C++

Upvotes: 5

Dan
Dan

Reputation: 13382

By default members of a struct are public i.e. visible to everything outside them whereas members of a class are by default private. This is the only difference between the two keywords (I believe).

Upvotes: 1

user142019
user142019

Reputation:

Probably because in a struct all members are public by default. In a class they are private by default.

If the author choose a class, he would've written this:

template <class Node_entry>
class Node {
public: // note this! <------------
// data members
Node_entry entry;
Node<Node_entry> *next;
// constructors
Node( );
Node(Node_entry, Node<Node_entry> *link = NULL);
};

Upvotes: 3

Alexandre C.
Alexandre C.

Reputation: 56956

struct and class both define classes, and can have methods, members, constructors, etc.

The only difference is that structure members are public by default, and that structures inherit publicly by default.

See this question.

Upvotes: 1

Related Questions