C++ Making functions not accessed by the client private - c++

Here is Main.cpp:
#include <iostream>
#include <cstdlib>
#include "linklist.h"
using namespace std;
void menu(List &);
int main()
{
//new list
List list;
menu(list);
return 0;
}
void menu(List &list)
{
char choice;
int item;
do {
system("CLS"); // for ise of std library
cout<<"\t Menu\n";
cout<<"\t\tOptions\n\n";
cout<<"\t\tInsert a Student (press I)\n";
cout<<"\t\tRemove a Student (press R)\n";
cout<<"\t\tDisplay List of Student (press D)\n";
cout<<"\t\tClear List (press C)\n";
cout<<"\t\tExit (press E)\n";
cout<<"What would you like to do ? Press the coresponding key:";
cin>>choice;
choice = toupper(choice);
cin.ignore();
switch(choice)
{
case 'I':
list.Insert();
break;
case 'R':
list.Remove();
break;
case 'D':
list.Display();cin.get();
break;
case 'C':
list.Clear();cin.get();
break;
}
Here is list.cpp
#include "linklist.h"
#include <iostream>
using namespace std;
// insert at begining of the linked list
void List::Insert()
{
int student_id;
short test_one,test_two;
float average;
cout << "Enter the Student's ID: "; cin >> student_id;
cout << "Enter the score of Test One: "; cin>> test_one;
cout << "Enter the score of Test Two: "; cin >> test_two;
average = (test_one + (double)test_two)/2;
// new node
Node* newnode = new Node();
newnode->setnode(student_id,test_one,test_two,average);
newnode->setnext(head);
head = newnode;
}
// deletes from the last node in the list
void List::Remove()
{
Node* curr = head;
if (curr = NULL) {
cout << "No nodes to remove\n ";
return;
}
else if (curr->getnext() == NULL ) // it only has 1 !
{
delete curr;
head = NULL;
}
else
{
Node *prev;
do
{
prev = curr; // the prev becomes the curr
curr = curr->getnext();
}while(curr->getnext() != NULL); // while the next one is not empty
prev->setnext(NULL);
delete curr; // delte the curr and it will repeat as prev becomes curr
// unill curr=NULL
}
}
// displays the nodes to the console
void List::Display()
{
Print(head);
}
void List::Print(Node* temp)
{
if (temp = NULL)
{
cout << "End" << endl;
return;
}else
{
temp->getnode();
Print(temp->getnext()); // these two steps will continue
} // until temp=NULL
}
// clears the linked list of all nodes
void List::Clear()
{
Node *temp = head; //store current head in temp
while(head != NULL)
{
head = head->getnext(); // set next head to head
delete temp; // delete current head in temp
}
}
Here is header file for the node class with functions:
#ifndef NODE_H
#define HODE_H
#include <iostream>
using namespace std;
// Here is the node class
class Node {
int student_id;
short test_one;
short test_two;
float average;
Node* next;
public:
Node(){}
void setnode(int student_id,short test_one,short test_two,float average)
{
student_id = student_id;
test_one = test_one;
test_two = test_two;
average = average;
}
void setnext(Node *link)
{
next = link;
}
void getnode( )const
{
cout << "The student's ID #: " << student_id << endl;
cout << "Score of Test One: " << test_one << endl;
cout << "Score of Test Two: " << test_two << endl;
cout << "The average: " << average << endl;
}
// returns address of the next node
Node* getnext()
{
return next;
}
};
#endif
Here is the header file for the class
#include "node.h"
#include <iostream>
class List
{
Node *head;
public:
List()
{
head = NULL;
}
void Insert();
void Remove();
void Clear();
void Display();
void Print(Node*);
};
Now what has to be done is a refactor of the following code so that:
"functions that are not accessed by the client should be private, mutator functions parameters are constant referenced, and all accessor functions are constants."
I've tired just switching to private, I've tried creating friends, and I have read something about runtime polymorphism and didn't try to implement because it did not seem to apply. I don't know where to start now because I'm under the impression that main.cpp is the client and it has to have access in order for this to work.
How would the above refactor ("functions that are not accessed by the client should be private, mutator functions parameters are constant referenced, and all accessor functions are constants.") work/look ?
After reading some of the comments and some more research. I've decided that setnode, getnode, getnext, setnext and Print should be private. They do not need any interaction with a user. Or I should say, that a user can incorrectly input parameters.
How about pass by reference ?
I'm starting to refactor but I'm still getting error's that the functions are private. Can anyone show a code snippet to refactor one of (or all that should be private) the functions to private so it works when its called by main.cpp ?

Related

While traversing the link list to read data my function prints up to penultimate node only, Suggest a way to print the whole list

I made a linked list in C++. For in which I have a function named: ListTraverse(). Which accepts a Node type pointer variable, where Node is my class. Please suggest me a method where it prints up to the last node.
Here is function call:
ListTraverse(&head);
And here is the function definition:
void ListTraverse(Node* node)
{
//Prints upto penultimate node
while (node->next != NULL)
{
cout << "\nNode details:\t"
<< node->read_data();
node=node->next;
}
}
And here you have the entire code.
#include <bits/stdc++.h>
#include <stdlib.h>
#include<typeinfo>
using namespace std;
class Node
{
private:
int data;
public:
Node *next;
void push_data(int x)
{
data = x;
}
int read_data()
{
return data;
}
};
void ListTraverse(Node *);
int main()
{
system("CLS");
//Creating Node type variables
Node head, second, tail;
int num, choice;
//Getting user input
cout << "Enter a number for head:\t";
cin >> num;
head.push_data(num);
cout << "Enter a number for second:\t";
cin >> num;
second.push_data(num);
cout << "Enter a number for tail:\t";
cin >> num;
tail.push_data(num);
//Assigning pointers to link up
head.next = &second;
second.next = &tail;
tail.next = NULL;
cout << "If you want to read data press 1:\t";
cin >> choice;
switch (choice)
{
case 1:
ListTraverse(&head);
break;
default:
cout << "Invalid choice";
break;
}
return 0;
}
//Funtion to print Data
void ListTraverse(Node* node)
{
//Prints upto penultimate node
while (node->next != NULL)
{
cout << "\nNode details:\t"
<< node->read_data();
node=node->next;
}
}
You should re-phrase your question. It seems that
my function prints up to penultimate node only
is the problem.
you wanted to print the whole list, not penultimate. And the fix is
void ListTraverse(Node* node)
{
//Prints upto the last node
while (node)
{
cout << "\nNode details:\t"
<< node->read_data();
node=node->next;
}
}

Creating Linked list insertion function but the code is not running

Unable to recognize the error in creating a linked list insertion function in linked list class the compiler giving this " error: qualified-id in declaration before '(' token But it seems like all the parenthesis are placed correctly.
#include <iostream>
using namespace std;
void additem();
void deleteitem();
void searchitem(int x);
struct student{
int data;
int * next;
};
student * head;
student * curr;
int main()
{
int x;
cout << "To add item type 1" << endl;
cin >> x;
switch(x)
{
case 1:
additem();
}
return 0;
}
void additem()
{
student * temp;
if(head == NULL)
{
temp = new student;
head = temp;
curr = temp;
temp->next = NULL;
cout << "Enter data" << endl;
cin >> temp->data << endl;
}
else if(head != NULL)
{
temp = new student;
curr->next = temp;
curr = temp;
temp->next = NULL;
cout << "Enter data" << endl;
cin >> temp->data ;
}
else{
break;
}
}
You're declaring a class and methods within main. This is not allowed (nested functions). linkedlist::additem needs to be defined before main.

Print a Doubly Linked List in Reverse

I have a list that is dynamically created based off of user input. I can add strings, and I can remove strings, but I am at a loss on how to properly print this in reverse.
Example:
input : First Second Last
output: Last Second First
I have tried a few things, and I have looked up what needs to be done, but I am having a tough time getting it correct.
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
// define a node for storage and linking
class node{
public:
string name;
node *next;
node *prev;
};
class linkedList{
public:
linkedList() :top(NULL){}
bool empty(){ return top == NULL; }
node *getTop(){ return top; }
void setTop(node *n){ top = n; }
void add(string);
int menu();
void remove(string);
~linkedList();
void reversePrint();
friend ostream& operator << (ostream&, const linkedList&); // default
output is in-order print.
private:
node *top;
node *end;
};
void main(){
linkedList l;
cout << l.empty() << endl;
int option = 0;
string s;
bool go = true;
while (go){
option = l.menu();
switch (option){
case 1: cout << "enter a name: "; cin >> s; l.add(s); break;
case 2: cout << "enter name to be deleted: "; cin >> s; l.remove(s); break;
case 3: cout << l; break;
case 4: cout << l.reversePrint(); break; // I am getting a Syntax error here
case 5: cout << "exiting" << endl; go = false; break;
}
}
system("PAUSE");
// l goes out of scope and calls ~linkedList()
}
void linkedList::reversePrint()
{
node *start_ptr = NULL;
node *current = start_ptr;
node *prev = NULL;
node *next = NULL;
while (current){
next = current->next;
current->next = prev;
current->prev = next;
prev = current;
current = next;
}
}
You didn't provide complete code (such as the implementation of linkedList::add()) so it's hard to give the correct answer...
According to your partial code, since the return type of reversePrint() is void, you can not cout it.
Therefore, in the switch block in main function should be:
case 4: l.reversePrint(); break;
I try to modify your code but not sure if it's correct since I don't have the code.
void linkedList::reversePrint()
{
node *current = end;
while (current){
cout << current->name << " ";
current = current->prev;
}
}

Error in adding element to the back of linked list

I am trying to add an element to the back of a linked list.
I am able to add the element and everything works fine on the first try but when i try to add another element, the previously added element becomes rubbish value.
The problem is solved when i replace the LinkedList::process_example(int choice,LinkedList &set) function in the main menu with exactly the same code in my function declaration. Can someone explain to me why????
#include <iostream>
#include <ctime>
using namespace std;
struct Node;
typedef void* VoidPtr;
typedef Node* NodePtr;
typedef char* ZodiacSign;
const int MAX=12;
struct Node
{
NodePtr next;
VoidPtr data;
};
class LinkedList
{
public:
LinkedList();
//~LinkedList();
void Addelement(VoidPtr);
void printSet();
int compareEqual(VoidPtr,VoidPtr);
void swap(int num,int x,ZodiacSign tempSign [MAX]);
void process_example(int choice);
int check_cardinality();
void Addelementfromback(VoidPtr);
private:
NodePtr head;
ZodiacSign getVP(VoidPtr);
};
int choice=1;
LinkedList set;
do {
cout<<endl
<<endl;
cout<<"Wish to try the following operation?"
<<endl
<<"1. Add an element to set"// the function to add to back of linked list
<<endl
<<"2. Check an element in set"
<<endl
<<"3. check carinality"
<<endl
<<"9. Quit"
<<endl
<<endl;
cout<<"Your choice : ";
cin>>choice;
cin.clear();
cin.ignore(200,'\n');
set.process_example(choice);
} while (choice !=9);
void LinkedList::process_example(int choice)
{
switch (choice)
{
case 1:
cout<<endl
<<endl
<<"Current S = ";
this->printSet();
cout<<"Enter an element :";
char element [30];
cin>>element;
cin.clear();
cin.ignore(200,'\n');
this->Addelementfromback(element);
cout<<endl
<<endl
<<"Current S = ";
this->printSet();
break;
case 3:
cout<<endl
<<endl;
cout<<"Current Set S = ";
set.printSet();
cout<<endl
<<"S has ";
int count=this->check_cardinality();
cout<<count
<<" elements";
}
}
void LinkedList::printSet()
{
NodePtr temp = head;
cout<<"{ ";
while (temp != NULL)
{
cout << getVP (temp -> data) << " , ";
temp = temp -> next;
}
cout<<" } ";
cout << endl;
}
void LinkedList::Addelementfromback(VoidPtr horoscope)
{
NodePtr temp = head;
while (temp->next != NULL)
{
temp=temp->next;
}
NodePtr element = new Node;
element->data=horoscope;
element->next=NULL;
temp->next=element;
}
As WhozCraig already mentioned you need to add the following lines to the constructor
Head = NULL;
and then you can add the something like this to the beginning of function Addelementfromback
If(Head == NULL)
{
Head = new Node;
Head->data = horoscope;
Head->next = NULL;
return;
}
you also need to change the following line in LinkedList::process_example
char elements[30];
to
char* elements = new char[30];

Linked Lists C++, output not showing in display function

#include <string>
using namespace std;
class PersonList
{
private:
char aName[7];
int aBribe;
PersonList *link;
public:
void addNodes();
void display();
};
#include <iostream>
#include <string>
using namespace std;
#include "mylink.h"
void PersonList::addNodes()
{
PersonList *temp2;
PersonList* startPtr = new PersonList();
PersonList* current = new PersonList();
PersonList *temp = new PersonList();//created the first node on the list
cout<<"Enter the person's name: ";
cin>>temp->aName;
cout<<"Enter the person's contribution: ";
cin>>temp->aBribe;
temp->link=NULL;//when i get last node, link will point to null(where am i in list?)
if(startPtr==NULL)
{
startPtr = temp;
current = startPtr;
}
else
{
temp2 = startPtr;
while(temp2->link!=NULL)
temp2 = temp2->link;
temp2->link=temp;
}
//}
}
void PersonList::display()
{
PersonList *temp;
PersonList *startPtr = this;
temp=startPtr;
while(temp != NULL)
{
cout<<temp->aName<<"\t\t"<<temp->aBribe<<endl;
temp = temp->link;
}
}
#include <iostream>
#include "mylink.h"
using namespace std;
int displayMenu (void);
void processChoice(int, PersonList&);
int main()
{
int num;
PersonList myList;
do
{
num = displayMenu();
if (num != 3)
processChoice(num, myList);
} while (num != 3);
return 0;
}
int displayMenu(void)
{
int choice;
cout << "\nMenu\n";
cout << "==============================\n\n";
cout << "1. Add student to waiting list\n";
cout << "2. View waiting list\n";
cout << "3. Exit program\n\n";
cout << "Please enter choice: ";
cin >> choice;
cin.ignore();
return choice;
}
void processChoice(int choice, PersonList& p)
{
switch(choice)
{
case 1: p.addNodes();
break;
case 2: p.display();
break;
}
}
My question is the display function is not displaying name and contribution that I enter.
Im using temp variable as a pointer node to call aName and aBribe. This goes through the list while it has not reached null. Nothing shows in output
You are creating a new list:
PersonList *startPtr = new PersonList();
and then showing that. So, naturally it is empty.
You have a similar problem in your addNodes method. You are adding nodes to a new list, then throwing it away, which is actually a memory leak.