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;
}
Does C++ standard has any say about such run-time anomalies?
No. Access control is purely compile-time, and affects which names may be used, not which functions may be called.
So in your example, you can access the name Base::Sayhi
, but not Derived::Sayhi
; and access to Base::Sayhi
allows you to virtually call any function that overrides it.
Why wouldn't standard enforce compiler implementors to have warning diagnostics?
The standard has nothing to say about warnings at all; it just defines the behaviour of well-formed code. It's up to compiler writers to decide what warnings might be useful; and warning about all private overrides just in case you didn't mean them to be overrides sounds like it would generate a lot of false positives.