Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 ?

like image 786
balas bellobas Avatar asked May 11 '11 09:05

balas bellobas


People also ask

How do you access private members from a derived class?

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 get derived as private member in derived class?

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.

Can a base class pointer access derived class function?

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.

Can a derived class pointer point to a base class object?

Derived class pointer cannot point to base class.


1 Answers

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.

like image 186
Hosam Aly Avatar answered Sep 22 '22 10:09

Hosam Aly