Question

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;
}
Was it helpful?

Solution

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.

OTHER TIPS

Access specification cannot be loosened it can only be tightened up.
Sayhi() is public in Base class so basically all classes deriving and overidding from it should expect the method to be public, there is no intrusion. The access specification for overidding functions is well specified since the method was declared public to begin with.

Even though your question has been answered by now, I would like to add a note.

While you consider this as an "anomaly" and would like to have diagnostics, this is actually useful: You can ensure that your implementation can only be used polymorpically. The derived class should only have a public ctor and no other public functions, all the re-implemented member functions should be private.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top