c++ - How can I access to a "parent" protected member? -


this "simulation" of code:

#include <string> #include <iostream>  using namespace std;  class { protected:     int test = 10; };  class c;  class b : public { 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 protected status type of test variable, since framework , don't have real "access".

i need create instance of class c b (which extend a), passing b , access (from c) param test of a.

is there fancy way doing it? within b can use test without problem...

the c class doesn't inherit b, b not parent, c class has no access protected members.

workaround

if control b , c not allowed touch comes framework, try:

class b : public { private:     c *c;  public:     b(); friend c;  // make c friend of b has access.   }; 

online demo

advise

despite there technical workaround achieve want, might not advisable so. idea of protected members it's implementation details relevant derived classes. opening friendship, create dependency implementation details not supposed have access to. you'd violate framework's design principle. possible @ own risk.

another approach add public getter protected element in b , in c refer public member (demo). it's better you'd still expose data you're not supposed to.


Comments