c++ - Is it safe to access Base protected member this way? -
i have 2 classes:
class base { protected: int x; }; class der: public base { void acc(base& b) { b.*(&der::x) = 5; } };
is safe access base protected member way (&der::x) ? i'm worried point wrong variable.
this way pass accessing protected member of base class object.
the above code:
for might find difficult understand below line
b.*(&der::x) = 5;
it can written as:
b.*(&(der::x)) = 5;
as scope resolution operator can omitted have 1 variable named x
in base , derived class.
b.*(&x) = 5;
which nothing taking address of x
, again dereferencing it. can written as:
b.x = 5;
which hope might aware of. code won't compile if use b.x
instead of 'b.*(&der::x) = 5;' 'x' protected , used bypass compiler rule prevents writing b.x = 5;
Comments
Post a Comment