ginos
ginos

Reputation: 23

Access protected members from a public derived class

I am getting an error when trying to access a protected member of a base class from a method of a derived class which inherits public.

I am passing by reference two objects of the base class to the method of the derived class and try to access the objects' protected member. However, the editor complains.

In sort, here is what I am trying to do:

class A {
protected:
  int x;
};

class B:public A
{
public:
  void test(A &obj1, A &obj2)
  {
    obj1.x = 1;
    obj2.x = 2;
  }
};

And this is the complain from the editor:

 int A::x
 protected member A::x (declared at line 5) is not accessible though "A" pointer or object.

What is wrong with my code and what can I do to correct it?

Thank you.

Upvotes: 0

Views: 1393

Answers (2)

I. Ahmed
I. Ahmed

Reputation: 2534

For class A the variable x is protected which will act like private for class A, so the member variable A::X is not accessible.

However, if you change the method

void test(A &obj1, A &obj2)

to

void test(B &obj1, B &obj2)

Then you can access the variable x from class B, as its available as protected as inheritance is public.

So, the whole code can be written like follows for accessing x in class B:

class A {
    protected:
        int x;
};

class B:public A
{
    public:
        void test(B &obj1, B &obj2)
        {
            obj1.x = 1;
            obj2.x = 2;
        }
};

Upvotes: 0

Ricardo Antunes
Ricardo Antunes

Reputation: 397

You can only access base class protected members of classes with the same type as the derived object. You will have to make a public method to obtain the member or other workaround. Imagine you had another class C, which inherited A as private. You could pass C to the B method as an A reference, but the base class members wouldn't be accessible. If the references passed to the B method where B references, then you would be able to access the protected members in them.

Upvotes: 1

Related Questions