Possible Duplicate:
Why can i access a derived private member function via a base class pointer to a derived object?
#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 does p->fn2()
call the derived class function even though fn2
is private in D
?
You can directly access the private member via its address in memory. If you're comfortable with it that is. You could have a function in the base class that returns the address of the private member and then use some wrapping function in the derived class to retrieve, dereference and set the private member.
Which access type data gets derived as private member in derived class? Explanation: It is a rule, that when a derived class inherits the base class in private access mode, all the members of base class gets derived as private members of the derived class.
Explanation: A base class pointer can point to a derived class object, but we can only access base class member or virtual functions using the base class pointer because object slicing happens when a derived class object is assigned to a base class object.
Derived class pointer cannot point to base class.
Access modifiers, such as public
, private
and protected
are only enforced during compilation. When you call the function through a pointer to the base class, the compiler doesn't know that the pointer points to an instance of the derived class. According to the rules the compiler can infer from this expression, this call is valid.
It is usually a semantic error to reduce the visibility of a member in a derived class. Modern programming languages such as Java and C# refuse to compile such code, because a member that is visible in the base class is always accessible in the derived class through a base pointer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With