Following code prints "I'm B!". It's a bit strange because B::foo() is private. About A* ptr we can say that its static type is A (foo is public) and its dynamic type is B (foo is private). So I can invoke foo via pointer to A. But this way I have access to private function in B. Can it be considered as encapsulation violation?
Since access qualifier is not part of class method signature it can lead to such strange cases. Why does in C++ access qualifier is not considered when virtual function is overridden? Can I prohibit such cases? What design principle is behind this decision?
#include <iostream>
class A
{
public:
virtual void foo()
{
std::cout << "I'm A!\n";
};
};
class B: public A
{
private:
void foo() override
{
std::cout << "I'm B!\n";
};
};
int main()
{
A* ptr;
B b;
ptr = &b;
ptr->foo();
}