Search code examples
c++inheritancepolymorphismencapsulation

Call private method from the world in c++


I realy don't understand why it works, but below code shows an example of calling private method from the world without any friend classes:

class A
{
public:
    virtual void someMethod(){
        std::cout << "A::someMethod";
    }
};
class B : public A
{
private:
    virtual void someMethod(){
        std::cout << "B::someMethod";
    }
};
int main(){
    A* a = new B;
    a->someMethod();
}

outputs:

B::someMethod

Doesn't it violates encapsulation rules in C++? For me this is insane. The inheritance is public, but the access modifier in derived class is changed to private, thus the someMethod() in class B is private. So in fact, doing a->someMethod(), we are directly calling a private method from the world.


Solution

  • Consider the following code, a modification of the code in the original question:

    class A
    {
    public:
        virtual void X(){
            std::cout << "A::someMethod";
        }
    };
    class B : public A
    {
    private:
        virtual void Y(){
            std::cout << "B::someMethod";
        }
    };
    int main(){
        A* a = new B;
        a->X();
    }
    

    It's easy to understand that it's legit to call X(). B inherits it from A as a public member. Theoretically if X() would call Y() this would be legit as well of course, although this is not possible because X() is declared in A which doesn't know Y(). But actually this is the case if X = Y, i.e. if both methods have the same name.

    You may think of it as "B inherits a public method from A, that calls a private method (of B) with the same name".