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

Possible duplicate:
Why can I access a derived private member function using a pointer to a derived class from a base class?

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

Why p->fn2() call a function of the derived class, although fn2 is private in D ?

+8
c ++ inheritance polymorphism access-modifiers
source share
4 answers

Access modifiers, such as public , private and protected , apply only at compile time. When you call a function through a pointer to a base class, the compiler does not know that the pointer points to an instance of the derived class. According to the rules that the compiler can infer from this expression, this call is valid.

Usually a semantic error reduces the visibility of a member in a derived class. Modern programming languages ​​such as Java and C # refuse to compile such code, because the element that is visible in the base class is always available in the derived class using the base pointer.

+5
source share

The call p->fn2() is evaluated at runtime depending on the type of object pointed to by p . At compile time, the compiler sees the call p->fn2() as a call to B::fn2() , and since B::fn2() is publicly available, the compiler does not report only an error. Only at runtime is the actual call to the function D::fn2() calculated.

This does not violate the Encapsulation principle, it is a C ++ function called Run-time Polymorphism or Dynamic Polymorphism

0
source share

When you execute p = new D , p->__vfptr now points to the beginning of the virtual function table D And since this happens at run time, therefore access specifiers do not come into play.

0
source share

From wikipedia :

In OOP, when a derived class inherits a base class, an object of the derived class can be assigned (or cast) as either being the base class or the type of the derived class. If there are methods of the base class overridden by the derived class, the method invocation behavior is ambiguous.

The distinction between virtual and non-virtual resolves this ambiguity. If the function in question is designated "virtual" in the base class, then the derived function of the class (if it exists). If it is not virtual, the base class function will be called.

NTN.

-2
source share

All Articles