Good Day! I'm currently trying to create a database that needs me to create two ADT. One of them has a private struct linkedlist created in this example
The problem is I can't seem to access or at least print out the values inside my struct in a function from another class
here is a sample code I derived from my original
#include <iostream>
using namespace std;
class A;
class B;
class A{
private:
struct Node{
int var1;
struct Node *next;
};
Node *head = NULL;
int var1 = 10;
friend class B;
public:
void CNode();
};
void A::CNode(){
Node *CPtr, *NewNode;
NewNode = new Node;
NewNode -> var1 = var1;
NewNode -> next = NULL;
if(!head){
head = NewNode;
}
else{
CPtr = head;
while(CPtr->next){
CPtr = CPtr->next;
}
CPtr->next = NewNode;
}
CPtr = head;
while(CPtr){
cout << "Class A: " << CPtr -> var1 << endl <<endl;
cout << CPtr -> next;
break;
}
}
class B{
A c;
public:
void Display();
};
void B::Display(){
//Problem lies here I think
A::Node *CPtr;
CPtr = c.head;
cout << "Class B Integration: " << CPtr -> var1 << endl;
}
int main()
{
A a;
B b;
a.CNode();
b.Display();
}
The problem lies within Display(). As you can see I'm trying to access my private struct LinkedList in another class and I have no clue or experience whatsoever on how to do it. I would truly be grateful for a solution.
First of all attribute c
in class B is private. There is nowhere in the B class to put that value. So I added a constructor that takes a reference to an instance of A.
What you were doing wrong: c
were always having a null pointer. Now something about raw references and pointers. Always check against nullptr
. Else, you''ll get undefined behaviour such as nothing displaying.
class B
{
A& c;
public:
B(A& c_) : c(c_){};
void Display();
};
void B::Display()
{
//Problem lies here I think
A::Node *CPtr;
CPtr = c.head;
if (CPtr != nullptr)
{
cout << "Class B Integration: " << CPtr->var1 << endl;
} else {
cout << "Class B's A attribute is null" << endl;
}
}
int main()
{
A a;
B b(a);
a.CNode();
b.Display();
}