Reputation:
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
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
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
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
Reputation: 24551
He wanted the default access to be public - that's the only difference between classes and structures in C++
Upvotes: 5
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
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
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