0

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?

Ed S.
  • 122,712
  • 22
  • 185
  • 265
user3554066
  • 77
  • 1
  • 6
  • I think you should look into the `friend` keyword. See this question for details: [When should you use 'friend' in C++?](http://stackoverflow.com/questions/17434/when-should-you-use-friend-in-c) – DaoWen Apr 20 '14 at 17:16
  • Please make your class `Node` a struct definition without any access controls (maybe scoped in `poly`, unless you think it has value of its own). That makes all your troubles go away. – Deduplicator Apr 20 '14 at 17:17
  • @Deduplicator - That's a good point. It might be best to just mark all the fields as `const` and make them public. – DaoWen Apr 20 '14 at 17:23
  • @DaoWen: `class poly` never hands out its `Node`s, so it does not need any access control. Making all `Node`s immutable though impedes many useful functions for `poly`, and runs counter to encapsulation. – Deduplicator Apr 20 '14 at 17:30
  • Please also take a look at `std::forward_list` and `std::list`. They are probably perfectly fine for your needs of lists. If they cannot serve for any reason (including you want to learn about implementing lists), you might want to avoid deviating from their interface anyway. – Deduplicator Apr 20 '14 at 17:35

1 Answers1

2

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.