0

The following code :

#include <iostream>

using namespace std;

class Base {
    protected :
        int a;
    public :
        Base() {};
        Base(int x) :a(x) {};
};

class Derived : public Base {
    public:
        Derived(int x) : Base(x) {};
 };


int main() {
    Derived b(11);
    int x;
    x=b.a;
}


does not compile because 'int Base::a' is protected within this context.

I know that the Derived class can not access a member of a different Base instance.

I read the following post Accessing protected members in a derived class (and others related posts). So I try different things. For example, I add a new constructor for Derived class.

Derived() {Base(static_cast<Derived*>(this)->a);};

But, as expected, without success.

Is there a mean (some modifers or something else) to access Base class protected field directly (a field in Base must be protected)?

Stef1611
  • 1,978
  • 2
  • 11
  • 30
  • I think you can create in the Derived class a method `getA()` public and inside the method, you call the `return a;` – vincenzopalazzo Aug 09 '19 at 11:58
  • @vincenzopalazza. I know that. But, I must create a method for each field I want to access. And, I would like to avoid that. – Stef1611 Aug 09 '19 at 12:02
  • `main()` can't access a protected member of the base class unless `Base` declares `main()` as a `friend`.. In your example, only member functions of `Derived` can access `protected` members of `Base`. – Peter Aug 09 '19 at 12:03
  • The entire point of making the members protected in the base class is that you should not access them from the outside. – molbdnilo Aug 09 '19 at 12:03
  • The question is not clear to me. What do you want to achieve here? The problem is just `x = b.a;` statement. And you can easily solve it with `using Base::x` in `Derived` or providing a *getter* for `a` member. How different instances of `Base` are related in this question? – BiagioF Aug 09 '19 at 12:05

1 Answers1

2

You can override the access specifier using a using directive

#include <iostream>

using namespace std;

class Base {
    protected :
        int a;
    public :
        Base() {};
        Base(int x) :a(x) {};
};

class Derived : public Base {
    public:
        Derived(int x) : Base(x) {};
        using Base::a;
 };


int main() {
    Derived b(11);
    int x;
    x=b.a;
}
MofX
  • 1,569
  • 12
  • 22
  • Thanks for answer. I am aware that `a` becomes public when it is accessed from `Derived` object but this solution is suitable for my needs. – Stef1611 Aug 09 '19 at 12:21