0

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.

SUGANTHI M
  • 35
  • 1
  • 1
    *The expected output is to print the value of x.* Why is it expected? – 273K Jul 06 '23 at 05:46
  • 3
    You create a *new* object in the `out` function. That object is unrelated to the `this` object. You can only access protected members of `this` object. – Some programmer dude Jul 06 '23 at 05:46
  • Also, remember that in C++ you don't have to (and rarely should) use `new` to create objects. By using `new` you have a memory leak. – Some programmer dude Jul 06 '23 at 05:47
  • Also please note that objects should rarely be just containers of values. Try to model your classes and inheritance hierarchy on *behavior*. – Some programmer dude Jul 06 '23 at 05:50
  • This is a more basic error, so not a direct duplicate of https://stackoverflow.com/questions/13723217/why-cant-i-access-a-protected-member-variable-of-a-base-class-passed-into-a-fun/13723325#13723325. But the answer given there applies here as well. `B::out` can access the protected member of its base class `A` sub-object, but not that of an unrelated `*p` object. – MSalters Jul 06 '23 at 13:24

0 Answers0