Module-level accessibility
Steven Schveighoffer
schveiguy at yahoo.com
Mon Oct 4 15:11:39 PDT 2010
On Mon, 04 Oct 2010 17:54:54 -0400, Jonathan M Davis <jmdavisProg at gmx.com>
wrote:
> On Monday, October 04, 2010 13:41:38 Steven Schveighoffer wrote:
>> To me, making it private doesn't do anything over protected. A derived
>> class can still call the function in question, because it has the
>> implementation. I don't see what the point is...
>>
>> A derived class from the derivative doesn't have access, but it can
>> always
>> override it in order to be able to call it (not a good workaround to
>> require).
>
> Except that part of the point is that because the private method is
> private in
> the base class, it _can't_ be called by derived classes. It can only be
> overridden.
Sure you can. Altered version of code from one of your articles:
#include <set>
class Set {
std::set<int> s_;
public:
void add (int i) {
s_.insert (i);
add_impl (i); // Note virtual call.
}
void addAll (int * begin, int * end) {
s_.insert (begin, end); // --------- (1)
addAll_impl (begin, end); // Note virtual call.
}
private:
virtual void add_impl (int i) = 0;
virtual void addAll_impl (int * begin, int * end) = 0;
};
class CountingSet : public Set {
private:
int count_;
virtual void add_impl (int i) {
addAll_impl(&i, (&i) + 1); // hey look, we can call a private
method!
}
virtual void addAll_impl (int * begin, int * end) {
count_ += std::distance(begin,end);
}
};
compiles with g++. So the private restriction does nothing significant
IMO.
Not responding to the rest of your points, since my argument is predicated
on you understanding this first ;)
In this example, BTW, I think the significance of private is the fact that
the s_ member is private. That *does* prevent derived classes from
altering the set except through the common interface.
Also, note that I'm not saying NVI isn't a valid or useful pattern (I've
used it in the past with success). I just think protected is a better
choice for the virtual methods.
-Steve
More information about the Digitalmars-d
mailing list