Compiler errors in C++ code

Hi All

Any idea what is wrong in the below code ?

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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#include <iostream>

using namespace std;

class SomeClass{
    protected:
    int data;
    friend class AnotherClass;
};

void SomeFunc(SomeClass sc)
{
    sc.data = 5;
}

class AnotherClass
{
    public:
    void Another(SomeClass sc)
    {
        sc.data = 25;
    }
    friend void SomeFunc(SomeClass sc);
};


int main(void)
{
    SomeClass sc;
    SomeFunc (sc);
    cout << sc.data;
}

}


OUTPUT: 
Compilation failed due to following error(s).main.cpp:21:8: error: ‘int SomeClass::data’ is protected within this context
   21 |     sc.data = 5;
      |        ^~~~
main.cpp:15:9: note: declared protected here
   15 |     int data;
      |         ^~~~
main.cpp: In function ‘int main()’:
main.cpp:39:16: error: ‘int SomeClass::data’ is protected within this context
   39 |     cout << sc.data;
      |                ^~~~
main.cpp:15:9: note: declared protected here
   15 |     int data;
      |         ^~~~
main.cpp: At global scope:
main.cpp:42:1: error: expected declaration before ‘}’ token
   42 | }
      | ^
just exactly what it says. you cannot use a variable from a class that is not public access unless you have special permissions (eg inheritance).
if you want to directly access 'data' then make it public. You can also provide methods that get or set the variable.

you also have a stray brace.
Last edited on
Here main() is not allowed to access the protected member data of SomeClass and also SomeFunc() is not allowed to access the protected member data of SomeClass.
Here main() is not allowed to access the protected member data of SomeClass and also SomeFunc() is not allowed to access the protected member data of SomeClass.


Exactly.

That's what you told the compiler when you declared data as protected:.

Either change the visibility of data to public: or do what @jonnin suggested.


Topic archived. No new replies allowed.