I am learning OOPS in C++. I try to access the class data member using pointer. But it throws error.
#include <iostream>
using namespace std;
class A
{
protected:
int x;
public:
A()
{
x=10;
}
};
class B:public A
{
public:
void out()
{
A *p=new A;
cout<<p->x;
}
};
int main()
{
B b;
b.out();
return 0;
}
The above code gives error as
error: ‘int A::x’ is protected within this context
| cout<<p->x;
Can anyone explain why the error occurs? The expected output is to print the value of x. Thanks in advance.
outfunction. That object is unrelated to thethisobject. You can only access protected members ofthisobject.newto create objects. By usingnewyou have a memory leak.B::outcan access the protected member of its base classAsub-object, but not that of an unrelated*pobject.