Java – Dynamic binding (bind) for private methods: Java vs. C++

Dynamic binding (bind) for private methods: Java vs. C++… here is a solution to the problem.

Dynamic binding (bind) for private methods: Java vs. C++

This is not allowed in Java :

class A { 
    public void method() {}
}

class B extends A { 
    private void method() {}
}

It produces a compilation error:

error: method() in B cannot override method() in A 
attempting to assign weaker access privileges; was public

However, this is allowed in C++:

class A { 
    public:
        virtual void method() {}
};

class B : public A { 
    private:
        void method() {}
};

int main(void) {
    A* obj = new B();
    obj->method();  B::method is invoked, despite it being private
}

What is the logic behind this behavior in C++?

Solution

Keep in mind that the visibility of methods is entirely solved at compile time, and C++ has no concept of runtime validators. What the compiler sees is a virtual A::method, which is not private. The concrete implementation is declared private, but this is only relevant if this implementation is called directly in a compiler-visible way, i.e. if you try to access it directly through B<

The logic is illustrated by the following example: Imagine if B inherited from A not publicly but privately—this is allowed in C++, and used when inheritance itself is an implementation detail, such as a stack class that inherits from a vector, but does not want to expose the vector interface. In that case, one of the features of the B::method is inaccessible, but the A::method works just fine even if the object is an instance of B .

As Kerrek SB says, here Java protects you from a class of errors at the cost of removing legitimate options.

Related Problems and Solutions