Assign the pointer of one class object to another class object c++ - 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();

Related

Modifying private pointer of object within same type (but different object) public method

I've been attempting to create a node class which mimics a node on a graph. Currently, storage of the predecessor and successor nodes are stored via a node pointer vector: std::vector<Node*> previous. The vectors for the predecessor/successor nodes are private variables and are accessible via setters/getters.
Currently, I am dealing with updating the pointer values when adding a new node. My current method to update the predecessor/successor nodes is through this method (the method is the same for successor/previous nodes, just name changes):
void set_next(std::vector<Node*> new_next) {
this->next.clear();
for (Node* node : new_next) {
this->next.push_back(node);
}
}
This works for the current node but I was wondering the best way to update the new_next nodes that are passed in, especially the most 'C++'-esque way to accomplish this. I have previously written a method which adds individual nodes to the successor/predecessor vector:
void add_next(Node* new_node, bool one_way = false) {
this->next.pushback(new_node);
if (!one_way) {
new_node->add_prev(this, one_way = true);
}
}
The one_way variable was used to determine the depth(?) of the add_next() call. If it is true, it will add to the successor set and then add to the predecessor set of new_node. Since the boolean value is set to false when the new_node->add_next() method call occurs, it will only add to the predecessor set and not attempt to call add_next()/add_prev() again. This solution does work, but I'd rather not have the one_way variable and would prefer that the method would be private.
Here is the structure of the class currently:
class Node {
private:
std::vector<Node*> previous;
std::vector<Node*> next;
boost::any data;
public:
std::vector<Node*> get_previous()
void set_previous(std::vector<Node*> new_previous)
std::vector<Node*> get_next()
void set_next(std::vector<Node*> new_next)
void add_prev(Node* new_node, bool one_way = false)
void add_next(Node* new_node, bool one_way = false)
}
Avoiding the one_way parameter, it seems my best solution would be to just create an add_next/add_prev method that only updates the current node, not the passed node, unlike the solution above. With this solution, when adding new nodes, I could call the inverse of the add_next/add_prev on the new node. However, I have an inkling there may be a better solution for this.
Thank you!
I think this should get you going (edge-cases left to you to figure out, if any):
template<typename T>
class Node {
// Everything made public for debugging purposes, change this to fit your needs
public:
std::vector<Node<T>*> previous;
std::vector<Node<T>*> next;
T data;
Node(T val) {
data = val;
}
void set_next(std::vector<Node<T>*>& new_next);
};
template<typename T>
void Node<T>::set_next(std::vector<Node<T>*>& new_next) {
next = new_next;
for (Node<T>* node : new_next)
node->previous.push_back(this);
}
int main() {
// Little proof of concept where 0 is parent to 1, 2, 3
Node<int> one = 1;
Node<int> two = 2;
Node<int> three = 3;
Node<int> zero = 0;
std::vector<Node<int>*> new_next = { &one , &two, &three };
zero.set_next(new_next);
return 0;
}
To sum up the differences:
Use templates, boost::any is non standard and is all around terrible for this task.
Leverage operators (= makes a copy of std::vectors).
Leverage reference types (this way you can modify the argument passed to your function).

Why are changes made to a pointer inside a function not visible outside the function?

I am implementing a linked list. There is a problem: when I change a pointer inside a function, the change is not visible outside of the function.
#include<bits/stdc++.h>
using namespace std;
//define
class List{
public:
int data;
List *next;
public:
List(int n){
this->data=n;
this->next=NULL;
}
};
void add(List *head,int data){
List * nn = new List (data);
head=nn;
}
// driver code
int main(){
List *head=NULL;
List * nn = new List (45);
head=nn;
cout<<head->data;
return 0;
}
This code is printing 45.
class List{
public:
int data;
List *next;
public:
List(int n){
this->data=n;
this->next=NULL;
}
};
void add(List *head,int data){
List * nn = new List (data);
head=nn;
}
// driver code
int main(){
List *head=NULL;
add(head,45);
cout<<head->data;
return 0;
}
This program prints nothing. It simply crashes.
This function:
void add(List *head, int data)
takes the head pointer by copy, so changes to the pointer inside the function are not visible to the caller. This means the pointer head in main is not pointing to valid memory, and dereferencing it invokes undefined behavior (which could cause the crash).
Make the function take the pointer by reference instead:
void add(List * &head, int data)
and now changing head inside the function changes head in the main function.
There are 2 issues in add method:
1) You need to accept pointer to reference (or pointer to pointer)
2) You need to add logic to traversal until the last node in the list and add the new node at the end. Otherwise everytime you are resetting list head with new node and new node is pointing to null and becoming one node list.
Similar implementation you can refer here https://github.com/alokkusingh/DataStructure . The implementation is in C (not C++)

Pointing a base pointer at a derived instance

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.

Trying to call a function

So I'm trying to call this function but not too familiar with dynamic data structures and linked lists so I keep getting it wrong. This is my code so far:
struct Country
{
string name;
double population;
};
struct Node
{
Country ctry;
Node * next;
};
Node * world;
void push(Country data, Node * & list);
int main ()
{
Country data;
Node list;
push(data, list);
return 0;
}
What am I doing wrong?
The push function takes a Node*&, which is a "reference to a pointer to a Node" (always read the type backwards, it helps. You are giving it list, which is a Node. The function gets the reference from that call, but you said you would give a reference to a pointer to a Node, so you want to make list in main a Node* and allocate and initialize memory for it, or you want to make another variable that is a Node* and point it to list (Node* ptr = &list;). The first option would be preferable in most cases.
Thanks for comment guys, I changed my code to this and it works now
struct Country
{
string name;
double population;
};
struct Node
{
Country ctry;
Node * next;
};
Node * world;
void push(Country data, Node * & world);
int main ()
{
Country data;
push(data, world);
return 0;
}

Trouble accessing class variables

I have a class "poly" and a class "node". The class poly is made from a linked list of nodes. I am trying to pass a poly to a function "printPoly" that will allow me to print the linked list of nodes. But I am having trouble accessing the variables of the nodes...
Here is my code:
class Node
{
private:
double coeff;
int exponent;
Node *next;
public:
Node(double c, int e, Node *nodeobjectPtr)
{
coeff = c;
exponent = e;
next = nodeobjectPtr;
}
};
class poly
{
private:
Node *start;
public:
poly(Node *head) /*constructor function*/
{
start = head;
}
void printPoly(); //->Poly *p1 would be the implicit parameter
};
void poly :: printPoly()
{
poly *result = NULL;
result = this;
double c;
int e;
Node *result_pos = res->start; //create ptr to traverse linked nodes
while(result_pos!= NULL)
{
c = result_pos->coeff; // I CANT ACCESS THESE???
e = result_pos->exponent;
printf(....);
result_pos = result_pos->next; //get next node (also can't access "next")
}
I think it has something to do with the fact that "coeff, exponent, and next" are private variables of the node class. But since my poly class is made up of nodes shouldn't it be able to access these?
Private variables and functions in a class can only be accessed by the function inside that class.
Anything you want to use from outside of that class (e.g. the way you are now) has to be public.