A
Adam H. Peterson
I just made an observation and I wondered if it's generally known (or
if I'm missing something). My observation is that static protected
members are essentially useless, only a hint to the user. They don't
actually protect any encapsulation or anything, and for all the actual
protection they offer, they might as well be public.
For example:
class B {
protected:
static int i;
static void f();
};
int B::i=0;
void f() {
}
Nothing stops anybody anywhere from reading or changing B::i or from
calling B::f(). All anyone needs to do is create a derived class like
so:
struct D : B {
static int &i() { return B::i; }
static void f() { B::f(); }
};
And, voila, the static protected method is (indirectly) publicly
accessible. Two lines of code overhead plus a line for each member to
be exposed. No one even has to create an instance, so private
constructors and destructors are no protection either.
Is this generally known (and is it correct)? Maybe people seldom make
protected static members, so it's rarely an issue in practice.
if I'm missing something). My observation is that static protected
members are essentially useless, only a hint to the user. They don't
actually protect any encapsulation or anything, and for all the actual
protection they offer, they might as well be public.
For example:
class B {
protected:
static int i;
static void f();
};
int B::i=0;
void f() {
}
Nothing stops anybody anywhere from reading or changing B::i or from
calling B::f(). All anyone needs to do is create a derived class like
so:
struct D : B {
static int &i() { return B::i; }
static void f() { B::f(); }
};
And, voila, the static protected method is (indirectly) publicly
accessible. Two lines of code overhead plus a line for each member to
be exposed. No one even has to create an instance, so private
constructors and destructors are no protection either.
Is this generally known (and is it correct)? Maybe people seldom make
protected static members, so it's rarely an issue in practice.