why can a base pointer point to derived object only under public inheritance?

前端 未结 3 921
野性不改
野性不改 2021-01-05 03:03

I think its because the base class data members and methods wont be accessible , but I\'d like some more clarity on this. Also, is this the reason why polymorphism (using vi

3条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-05 03:35

    Actually, a pointer to base can point to a derived class even if the base is private. The thing is that such a conversion is impossible from outside the class. However, it's still possible to perfrom such a conversion in a context where the base is accessible.

    Example:

    #include 
    using namespace std;
    
    struct Base
    {
        void foo() const {
            cout << "Base::foo()\n";
        }
    };
    
    struct Derived : private Base
    {
        const Base* get() const {
            return this; // This is fine
        }
    };
    
    int main()
    {
        Derived d;
        const Base *b = &d; // This is illegal
        const Base *b = d.get(); //This is fine
        b->foo();
    }
    

    Live example

    Live example with virtual call

提交回复
热议问题