c++ - Confusion regarding protected member functions and derived class access -
c++ - Confusion regarding protected member functions and derived class access -
i having give-and-take coworker why next not compile in visual studio 2008:
class base of operations { protected: virtual void f(){} }; class : public base of operations { public: void fa(base* pb) { pb->f(); // error c2248: 'base::f' : cannot access protected fellow member declared in class 'base' } }; he thinks reasonable think it's unusual restriction given, if wanted base , of derived classes closed system, still need create of base's members public can talk each other through shared interface derived publicly.
is there utilize case i'm not thinking of allowing access these protected members break nature of protected members?
if compiler allows such thing, can break encapsulation. think this:
base b; foo; foo.fa(b); // can access/modify protected elements of `b` in case, there no relation between derived object foo , base of operations b, can utilize derived access "guts". should not possible (at to the lowest degree imho).
just doing f() within a.fa() ok, since modify base of operations part of a, , not un-related object.
to more specific, can write "wrapper" disable protected class:
#include <iostream> class base of operations { public: // protected in case, public here compiles int x{42}; public: int getx() {return x;} }; template<typename t> // wrapper class disableprotected: public t { public: void modify(base* b) { b->x = 24; } }; int main() { base of operations base; std::cout << base.getx() << std::endl; disableprotected<base> foo; foo.modify(&base); // can modify base of operations std::cout << base.getx() << std::endl; } c++ visual-studio inheritance
Comments
Post a Comment