TITLE: does private virtual make sense? (Newsgroups: comp.lang.c++, 8 Oct 97) TIM: Tim D. > > I wrote a class something like this: > > Class InputClass; > > class BaseClass > { > private: > virtual bool vf(InputClass *TheInput) = 0; > public: > bool f(InputClass *TheInput) > { // guard function for vf() > if (TheInput==NULL) return false; > return vf(TheInput); > } > } > > class ADerivedClass : public BaseClass > { > private: > bool vf(InputClass *TheInput); > } > > My coworker came to me and said "The subclass isn't suppose to see a > private member, so it doesn't make sense to have a private, virtual > function." But, as far as I could tell, the compiler had no problem > with it. So, for his sake, I changed the function to "protected." BECKER: Pete Becker Find a new coworker, and don't change a design just because someone who doesn't know what they're talking about claims that it doesn't make sense. TIM: > None of the books I have looked at say anything relating "virtual" to > protection...and very little about protection being different for the > same named function between derived and base class; BECKER: The reason no books say this is that it isn't true. Access control is independent of virtualness. Making a member private means that only other members and friends of the class containing that member can access it. In your case this means that only member functions of BaseClass can call BaseClass::vf. Making vf virtual says that derived classes can override that function, so that calls from members of BaseClass to the function vf() will call the version defined in the derived class. The claim that a "subclass isn't supposed to see a private member" is simply wrong. The name is visible in the derived class, but the derived class cannot use it. To see what this means, try this: class Base { private: int i; }; class Derived : public Base { public: int f() { return i; } }; The compiler will complain that 'i' is not accessible, not that it can't "see" it. The only problem that you might run into by making vf private is that the derived class' version of vf() can't call the base version. If that's your intention, then making BaseClass::vf private is exactly the right thing to do.