Consider the below code snippet.
The method Sayhi() is having public access in class Base.
Sayhi() has been overridden as a private method by the class Derived.
In this way, we can intrude into someone's privacy and C++ has no way to detect it because things happen during run-time.
I understand it is "purely" compile-time check. But when using some thick inheritance hierarchy, programmers may incorrectly change access specifiers. Shouldn't the standard have some say atleast? some kind of warning message.
Why doesn't the compiler issue atleast a warning message whenever access specifier of overridden or virtual functions differ?
Q1. Does C++ standard has any say about such run-time anomalies?
Q2. I want to understand from C++ standard's perspective, why wouldn't standard enforce compiler implementors to have warning diagnostics?
#include <iostream>
class Base {
public:
virtual void Sayhi() { std::cout<<"hi from Base"<<std::endl; }
};
class Derived : public Base
{
private:
virtual void Sayhi() { std::cout<<"hi from Derived"<<std::endl; }
};
int main() {
Base *pb = new Derived;
// private method Derived::Sayhi() invoked.
// May affect the object state!
pb->Sayhi();
return 0;
}