c++ - why can a base pointer point to derived object only under public inheritance? -
i think because base class data members , methods wont accessible , i'd more clarity on this. also, reason why polymorphism (using virtual functions) possible under public inheritance?
actually, pointer base can point derived class if base private. thing such conversion impossible outside class. however, it's still possible perfrom such conversion in context base accessible.
example:
#include <iostream> using namespace std; struct base { void foo() const { cout << "base::foo()\n"; } }; struct derived : private base { const base* get() const { return this; // fine } }; int main() { derived d; const base *b = &d; // illegal const base *b = d.get(); //this fine b->foo(); }
Comments
Post a Comment