markzzz
markzzz

Reputation: 47945

How can I access to a "parent" protected member?

This is a "simulation" of my code:

#include <string>
#include <iostream>

using namespace std;

class A
{
protected:
    int test = 10;
};

class C;

class B : public A
{
private:
    C *c;

public:
    B();

};

class C
{
public:
    C(B *b) {
        cout << b->test;
    }
};

B::B() {
    c = new C(this);
}  

int main()
{
    B();
}

I can't touch the protected status type of that test variable, since is from another Framework and I don't have real "access".

I need to create an instance of class C from B (which extend A), passing B to it and access (from C) to the param test of A.

Is there a fancy way for doing it? Within B I can use test without any problem...

Upvotes: 3

Views: 107

Answers (2)

rocambille
rocambille

Reputation: 15966

You can also add a public accessor in B:

class B : public A
{
private:
    C *c;

public:
    B();
    int get_test() const { return this->test; }
};

Upvotes: 3

Christophe
Christophe

Reputation: 73376

The C class doesn't inherit from B, so B is not a parent, so the C class has no access to the protected members.

Workaround

If you control B and C but are not allowed to touch A which comes from another framework, you could try:

class B : public A
{
private:
    C *c;

public:
    B();
friend C;  // Make C a friend of B so that it has access.  
};

Online demo

Advise

Despite there is a technical workaround to achieve what you want, it might not be advisable to do so. The idea of protected members is that it's implementation details only relevant to derived classes. By opening it with a friendship, you create a dependency to implementation details you are not supposed to have access to. So you'd violate the framework's design principle. Possible but at your own risk.

Another approach could be to add a public getter to the protected element in B and then in C refer to this public member (demo). It's better but you'd still expose data that you're not supposed to.

Upvotes: 5

Related Questions