c++ - Access a derived private member function from a base class pointer to a derived object -


possible duplicate:
why can access derived private member function via base class pointer derived object?

#include <iostream> using namespace std;  class b { public:   virtual void fn1(void) {cout << "class b : fn  1 \n"; }   virtual void fn2(void) {cout << "class b : fn  2 \n"; } };  class d: public b {     void fn1(void) {cout << "class d : fn 1 \n"; } private:     void fn2(void) {cout << "class d : fn 2 \n"; } };  int main(void) {     b *p = new d;      p->fn1();     p->fn2(); } 

why p->fn2() call derived class function though fn2 private in d ?

access modifiers, such public, private , protected enforced during compilation. when call function through pointer base class, compiler doesn't know pointer points instance of derived class. according rules compiler can infer expression, call valid.

it semantic error reduce visibility of member in derived class. modern programming languages such java , c# refuse compile such code, because member visible in base class accessible in derived class through base pointer.


Comments

Popular posts from this blog

c# - how to write client side events functions for the combobox items -

exception - Python, pyPdf OCR error: pyPdf.utils.PdfReadError: EOF marker not found -