Pointing a base pointer at a derived instance - c++

I'm working on my final project for C++ and my professor specified that we had to have three class files for a linked list.
The first named LinkedList holds the head and the tail, as well as two overloaded operators in which we have to use the list as an array, and add an element to the end of the array.
The second named Node holds the two generic values Seat and Row.
The third and final named RNode holds the values of the next, previous spots in the list, as well as reservation status.
My problem is when using my LinkedList.cpp, defining all of the functions, I cannot figure out how to set node equal to the head, because the types are different. I can set the next node in the list with tempNode.setNext(Head);. But when I try to do tempNode = tempNode.getNext() it says the types are not the same. What is an easy way for me to make this work?
Here is my code.
This is supposed to use the Linked List as an array and return the pointer to the Node correlating with the integer passed in.
int& LinkedList::operator[] (const int &middle) {
RNode *tempNode;
tempNode->setNext(Head);
tempNode = tempNode->getNext(); // Error here
for (int i = 0; i < middle; i++) {
}
}
Here are the three class files I have currently made.
Linked List Class
#ifndef LINKEDLIST_H_INCLUDED
#define LINKEDLIST_H_INCLUDED
#include "Node.h"
class LinkedList {
private:
Node* Head; // Head of linked list
Node* Tail; // Tail of linked list
public:
// Constructors
LinkedList(); // Set default values
LinkedList(Node*, Node*); // Set values passed in to head and tail
int& operator [] (const int &); // Overloaded [] operator PAGE 854 HOW TO USE THIS
// Treat list like an array.
// First node will be [0]
// Return pointer to node indicated inside of brackets
Node& operator += (const Node &); // Overloaded += operator
// Adds a node to the end of the linked list
// Head
void setHead(Node*); // Sets head of list
Node* getHead(); // Returns the head of list
// Tail
void setTail(Node*); // Sets tail of list
Node* getTail(); // Returns tail of list
};
#endif // LINKEDLIST_H_INCLUDED
Reservation Node Class
#ifndef RNODE_H_INCLUDED
#define RNODE_H_INCLUDED
#include "Node.h"
using namespace std;
class RNode : public Node {
private:
Node* Next; // Next node pointer
Node* Prev; // Previous node pointer
bool reservationStatus(); // Reservation status
public:
// Constructors
RNode(); // Sets default values
RNode(Node*, Node*, bool); // Takes values passed in and sets them
// Overloaded operators
friend ostream &operator << (ostream &, Node*); // Prints out correct symbol based on reservation status
friend istream &operator >> (istream &, Node*); // Prints correct symbol based on reservation status .
// Next
void setNext(Node*); // Sets next node in list
Node* getNext(); // Returns next node in list
// Prev
void setPrev(Node*); // Sets previous node in list
Node* getPrev(); // Returns previous node in list
// Reservation Status
void setReservationStatus(bool); // Sets reservation status of a current node
bool getReservationStatus(); // Returns reservation status
};
#endif // RNODE_H_INCLUDED
Node Class
#ifndef NODE_H_INCLUDED
#define NODE_H_INCLUDED
class Node {
protected:
int row;
int seat;
public:
// Constructors
Node(); // Sets default values
Node(int, int); // Sets row and seat to values passed in
// Row
void setRow(int); // Sets row for current node
int getRow(); // Gets row for current node
// Seats
void setSeat(int); // Sets seat for current node
int getSeat(); // Gets seat for current node
};
#endif // NODE_H_INCLUDED
In summary, how can I match the types so that I can set RNode tempNode equal to a Node? This is very confusing and I can't really find a good explanation on how to solve this.
Keep in mind, according to my instructions I have to have the classes created this way. If it were up to me, I would have combined the RNode and Node class.

Related

Linked list overwrites the previous value

I want to create a linked list with classes. I have two classes, one LinkedList and another LinkedNode. My problem is that my function InsertAtEnd always delete the current node. So when I want to print my linked list, I can't see anything.
I know thanks to debugger that in the function InsertAtEnd, we don't enter in the while loop, this is the problem. But after several attemps I can't resolve my problem.
This is my code:
void LinkedList::InsertAtend(int data)
{
LinkedNode* node = new LinkedNode();
node->setData(data); node->setNext(nullptr);
LinkedNode* tmp = _header;
if (tmp != NULL)
{
while (tmp->getNext() != nullptr)
{
tmp = tmp->getNext();
}
tmp->setData(data);
tmp->setNext(nullptr);
}
else
{
_header = node;
}
}
My class LinkedNode:
class LinkedNode
{
public:
LinkedNode();
~LinkedNode();
void setData(int data);
void setNext(LinkedNode* next);
int getData() const;
LinkedNode* getNext() const;
private:
int _data;
LinkedNode* _next;
};
My class LinkedList:
#pragma once
#include
#include "LinkedNode.h"
using namespace std;
class LinkedList
{
public:
LinkedList();
~LinkedList();
void PrintList();
void InsertAtend(int data);
void PrintList() const;
private:
LinkedNode* _header;
};
Thanks for your help !
tmp->setData(data);
Your tmp is not the node that you're trying to add, but the last in your list.
tmp is the last Node, so if you don't want to delete it you shouldn't write value data in it. You should link it with the new Node, which you named node.
Instead of
tmp->setData(data);
tmp->setNext(nullptr);
You should write
tmp->setNext(node)
At the end of the loop, the tmp is the last node in the current list. As you want to add the new node after the last node, you need to
tmp->setNext(node);
to append it (and not set the data as the data are already set to the new node).
Also note that you actually do not need to iterate through the entire list at all, if you keep another member variable to the current end of the list (_tail). Then you can access it directly and simply append and update.

No Such File Or Directory Exists

I'm getting the error no such file or directory exists and it is confusing the hell out of me. I don't want help filling in my methods or anything, that I want to do for myself. I want to fix this error so that I can get started on my project.
This is the error I get:
My Error
Here is my code where the error takes place. If you need anything else, I will gladly update my question, or provide relevant information. Thanks to anyone who helps
#ifndef _DLINKEDLIST_H_
#define _DLINKEDLIST_H_
#include <cstdlib>
#include <stdexcept>
#include <string>
using namespace std;
// template class for doubly-linked list node
template <class T>
class Node
{
public:
T data;
//string data;
Node<T>* prev;
Node<T>* next;
// default constructor
//template <class T>
Node(T value)
{
data = value;
prev = NULL;
next = NULL;
}
};
// DLinkedList class definition
template <class T>
class DLinkedList
{
private:
// DLinkedList private members
int size; // number of items stored in list
Node<T>* front; // references to the front
Node<T>* back; // and back of the list
// helper function for deep copy
// Used by copy constructor and operator=
void CopyList(const DLinkedList& ll);
// helper function for deep delete
// Used by destructor and copy/assignment
void DeleteList();
public:
// default constructor
DLinkedList();
// copy constructor, performs deep copy of list elements
DLinkedList(const DLinkedList& ll);
// destructor
~DLinkedList();
// MUTATORS
// Inserts an item at the front of the list
// POST: List contains item at position 0
// PARAM: item = item to be inserted
void InsertFront(T item);
// Inserts an item at the back of the list
// POST: List contains item at back
// PARAM: item = item to be inserted
void InsertBack(T item);
// Inserts an item in position p (0-indexed)
// Throws exception for invalid index
// PRE: 0 <= p <= size
// POST: List contains item at position p
// PARAM: item = item to be inserted, p = position where item will be inserted
void InsertAt(T item, int p);
// Removes and returns an item from position p (0-indexed)
// Throws exception if list is empty or index invalid
// PRE: 0 <= p < size
// POST: Item is removed from list
// PARAM: p = position from where item will be removed
T RemoveAt(int p);
// Removes duplicates from the list, preserving existing order of remaining items.
// The first occurrence of any duplicate (relative to the front of the list)
// is the one which remains.
// We have not yet learned about efficiency so you may implement this in any way
// as long as the resulting list satisfies the requirement above.
// PRE:
// POST: List contains no duplicates, front and back point to the appropriate nodes
// PARAM:
void RemoveDuplicates();
// ACCESSORS
// Returns size of list
int Size() const;
// Returns whether the list is empty
bool IsEmpty() const;
// Returns existence of item
bool Contains(T item) const;
// Returns item at index (0-indexed)
// Throws exception for invalid index
T ElementAt(int p) const;
// OVERLOADED OPERATORS
// overloaded assignment operator
// must work in the following cases:
// list2 = list1 -> general case
// list2 = list2 -> should do nothing
DLinkedList& operator=(const DLinkedList& ll);
};
#include "dlinkedlist.cpp"
#endif
Answer was a quick and easy #include "..\srcdlinkedlist.cpp"
instead of #include "dlinkedlist.cpp"

Linked list,Confused about Function that adds node to head of the list

I have a question about a function that adds a creates/adds a new node to the top of the list. Here is the set up.
A head is created in the main program. We set the list to Null
IntNode* head = new IntNode(3,NULL);
My question is about the function that adds a node to the top of the list. Assumes that there is at least one node in the list.(the one we just created)
void headInsert(IntNodePtr& head, int theData)
{
head = new IntNode(theData, head);
}
I know it creates a new node and makes the pointer already declared in the main program, which is passed, point to the new node. However I am confused about he "head" part on the parameter in the constructor(not the headInsert function). I am confused about what exactly is being passed when we pass head in the IntNode constructor above. That head sets the variable link, to point to what head is pointing to correct? ******My question is, Does it first set *link(the class variable) to point to what head is pointing to, in this case the node with the number 3 whose list points to NULL, AND THEN makes head point to the new NODE? So in other words the right part of the assignment is done first? I'm just very confused as to what is being passed in when we create the new node.
class IntNode
{
public:
IntNode( ) {}
IntNode( int theData, IntNode* theLink)
: data(theData), link(theLink) {}
IntNode* getLink( ) const { return link; }
int getData( ) const { return data; }
void setData( int theData) { data = theData; }
void setLink(IntNode* pointer) { link = pointer; }
private:
int data;
IntNode *link;
};
void headInsert(IntNodePtr& head, int theData)
{
head = new IntNode(theData, head);
}
The evaluation of the sides of the assignment -
head
and
new IntNode(theData, head)
is not ordered at all, but prior to performing the assignment, both sides have been evaluated completely.
Since neither side modifies the value of head, the results are the same regardless of the order of evaluation.

Assign the pointer of one class object to another class object c++

so I am very new to C++ programming so I apologize beforehand if I am asking something trivial. My assignment is to add, multiply and evaluate polynomials where each term of a specified polynomial is represented by a Node class with private variables: double coefficient, int power and Node *next.
class Node{
private:
double coef;
int power;
Node *next;
public: blah
}
The head to that linked list (for each polynomial), is to be stored in an array of Poly objects where the only private variable in my Poly class is Node *head.
class Poly{
private:
Node *head;
public:poly functions;
}
The user is to select the polynomial they want to work with by selecting an element from my polynomial array, and this will give the head to the selected polynomial.
poly_array[n];
However my issue now is that the element of this array is of object Poly and I want to make it of class Node so I can actually extract its contents of the class and use this method to transverse through the nodes of the selected polynomial(s).
This is the code I have tried to implement to make this work but my function call of convert poly returns garbage. I am lost as to what method I should try next. Thank you in advance.
This is where I try to first transverse a polynomial to display its contents.
void init_polydisplay(vector<Poly*> polynomial_array, int numofpolys)
{
Poly *polyobject;
Node *polyhead;
for (int n = 0; n < numofpolys; n++)
{
temp3.getnodehead();
polyhead=polyobject->convertPoly(polynomial_array[n]);
}
}
My attempt at trying to return Node* versus just the head of the polynomial.
Node* Poly::convertPoly(Poly* tmp)
{
return (Node *) tmp;
}
You can define a get_head() function in Poly
class Poly{
private:
Node *head;
public:
Node * get_head()
{
return head;
}
};
and use it this way:
polyhead = polynomial_array[n]->get_head();

Eclipse complains about recursive function call

A simple binary search tree class declaration:
#include <vector>
#include <stdio.h>
// Provides various structures utilized by search algorithms.
// Represents an generalized node with integer value and a set of children.
class Node {
protected:
std::vector<Node*> children;
int value;
public:
//Creates a new instance of a Node with a default value=-1.
Node(){value = -1;}
//Creates a new instance of a Node with a specified value.
explicit Node(int value){this->value = value;}
virtual ~Node(){delete children;}
//Adds new Node with specified value to the list of child nodes. Multiple
//children with the same value are allowed.
//Returns added node.
virtual Node* Insert(int value);
//Removes first occurrence of a Node with specified value among children.
virtual void Remove(int value);
};
// Represents a binary search tree node with at most two children.
class BTNode: public Node {
public:
//Creates a new instance of a BTNode with a default value=-1.
BTNode():Node(){}
//Creates a new instance of a BTNode with a specified value.
explicit BTNode(int value):Node(value){}
//Adds new BTNode with specified value to the list of child nodes in an
//ordered manner, that is right child value is >= value of this node and
//left child value < value of this node.
virtual BTNode* Insert(int value);
//Removes first occurrence of a Node with specified value from the tree.
virtual void Remove(int value);
//Returns a node with specified value.
virtual BTNode* Search(int value);
};
And eclipse complains about it's definition:
BTNode* BTNode::Search(int value){
if (this->value == value) return *this;
//Determines whether value is in left(0) or right(1) child.
int child = this->value > value ? 0 : 1;
if (children[child] != NULL)
return children[child]->Search(value);
return NULL;
}
exactly where the call children[child]->Search(value) takes place with a message "method Search could not be resolved". Build runs just fine (no compilation errors whatsoever). What's the problem with that?
P.S.:Haven't tried running the code,yet. Working on it.
Search is part of the BTNode interface but it is not part of Nodes interface, children is a vector of Node* so it is not valid to call Search on a Node *. If it makes sense for Node to have a Search method then adding it to Node would fix that issue. If not then you need to rethink your design and that is probably beyond the scope of this question.
There are also a few other issues. You have:
virtual ~Node(){delete children;}
but children is not a pointer it is a std::vector<Node*>. You need to iterate over the vector and call delete each element. In Search you have this:
if (this->value == value) return *this;
but Search returns a BTNode* so it should be:
if (this->value == value) return this ;