Scope problem

here is a program which i have made , it does nothing(main is empty)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
using namespace std;

class roh

{

class node
{
int data;
node * link;
}*p;

void create()
{
p=new node;
p->data=11;
}
};

int main()
{
return 0;
}


there is a error in line 17 that p->data=11; is not accessible.
Plz help , tell me why it is happening and how to correct it.
Last edited on
The default visibility for members of a class is private.

i.e. the following would be equivalent to what you have:

1
2
3
4
5
6
class node
{
private:
    int data;
    node * link;
} *p;

When a member is private, it cannot be accessed from outside the class (unless the function/method/class doing the accessing is a friend).

If you want the node member variables to have private visibility, then you should provide accessor methods for others to obtain and/or modify them, i.e.:

1
2
3
4
5
6
7
8
9
10
11
12
class node
{
private:
    int data;
    node * link;

public:
    int getData();
    void setData(int newData);
    node* getLink();
    void setLink(node* newLink);
};

where the "get" methods access their respective members and the "set" methods modify them.

If you want the visibility of all the members of node to be public, then it may be better to make it a struct.
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
class roh

{

    class node
    {
        /*
        Unless otherwise specified the default access mode
        for a class is private.
        So these next two members are private members of
        the node class
        */
        
        int data;
        node * link;
       
    }*p;

    
    void create()
    {
        /*
        The next two lines are  problems because:
        this create function is a member of  class roh - and
        it is trying to access a private member (data) of the node class
        
        to solve this problem
        class roh will need to be a friend of the node class 
        or, the relevant members of  node class will have to be declared public
        */
        p=new node;
        p->data=11;
    }
};
Last edited on
ok ok ok :) thank u vry much :)
Topic archived. No new replies allowed.