Chichi
Chichi

Reputation: 25

How do I convert "struct Node" into "class Node"?

For example, I have

struct Node
{
    string firstName;
    string middleI;
    string lastName;
    string phoneNum;
    Node *next;
};

I want to change it so instead of having "struct Node", I change it to "class Node". I feel like what I have isn't right so far, which is:

class Node
{
private:
  string firstName;
  string middleI;
  string lastName;
  string phoneNum;

  Node *next;

public:
  Node(string f, string mi, string sur, string ph){
        firstName = f;
        middleI = mi;
        lastName = sur;
        phoneNum = ph;
        next = NULL;
  }
};

If I were to change from struct Node to class Node, will it affect my linked list functions? (My linked list functions are printing out a linked list and reading in data.)

Upvotes: 1

Views: 351

Answers (1)

eerorika
eerorika

Reputation: 238491

I want to change it so instead of having "struct Node", I change it to "class Node"

The only difference between struct and class keywords is the default access specifier of the class that is being defined. Therefore, if your only goal is to change the keyword you use to define the class, then all you need to do is specify the access specifier to match the original struct definition:

class Node
{
public:  // notice this
    string firstName;
    string middleI;
    string lastName;
    string phoneNum;
    Node *next;
};

If I were to change from struct Node to class Node, will it affect my linked list functions?

If the definition remains equivalent, like in my example, then nothing is affected, because it is semantically equivalent.

If you change the access of the members to private like in your attempt, then any non-member function using those member names will become ill-formed. If your goal is to make your data members private, then you'll need to use member functions to access them.

Upvotes: 1

Related Questions