Here is a very simple code demonstrating how 'protected' is used
# include <iostream>
using namespace std;
class A
{
protected :
int a;
};
class B : public A
{
public :
void f_1() // *
{
a = 10;
cout << a;
}
};
int main()
{
B obj_2;
obj_2.f_1(); // **
return 0;
}
*This function here, f_1(), puts the value 10 inside the variable 'a' of object obj_2 present here **. That is, it changes the value of 'a' of the invoking object
But mind you, 'a' is inherited as it is protected in the base class 'A'
But if I change my program to this, that is, only change the function f_1() to this
# include <iostream>
using namespace std;
class A
{
protected :
int a;
};
class B : public A
{
public :
void f_1()
{
A obj; // This part changed!!
obj.a = 20; // Made a seperate object,
cout << obj.a; // instead of using the invoked object
}
};
int main()
{
B obj_2;
obj_2.f_1();
return 0;
}
Then it gives this error error: `int A::a' is protected
So can someone please explaing why this error is occuring?