Re: Possible encapsulation issue
On 14 Sep., 01:05, Amit Mishra <amitk...@gmail.com> wrote:
Consider this program.
[..]
Output: Derived foo()
So it is possible to access a private data member this way.
This is not an oversight, but an intended design choice.
Virtual functions are always observable and the overriding
mechanism is immune against access control. Even a
*private* virtual function in the base class will be overriden
by a corresponding function signature in the derived class
as in the following variation of your example:
#include <iostream>
class Base {
private:
virtual void foo() { std::cout << "Base foo()\n"; } // Private here!
public:
void bar() { foo(); }
};
class Derived : public Base {
private:
void foo() { std::cout << "Derived foo()\n"; } // OK: Final
overrider
};
int main()
{
Derived d;
Base* bp = &d;
bp->bar(); // OK: Writes "Derived foo()\n"
}
Additional to that, virtual functions in templates also
have special rights: An implementation is allowed to
instantiate each virtual function implementation, even
if it is not used - in contrast to all other member
functions of a class template. This means that every
declared virtual function *must* be defined, *unless*
it is a pure virtual functions.
HTH & Greetings from Bremen,
Daniel Kr=FCgler
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]