Thursday, 27 December 2012

Access private method out side the block/class


#include<iostream>
using namespace std;
class Base {
public:
    virtual int fun(int i) { cout << "Base::fun(int i) called"; return 0; }
};
class Derived: public Base {
private:
    int fun(int x)   { cout << "Derived::fun(int x) called";  return 0;}
};
int main()
{
    Base *ptr = new Derived;
    ptr->fun(10);                    //Private method of derived will be called out side the class.
    return 0;
}

output:

Derived::fun(int x) called

This is not violation of oops. In C++, virtual & access specifier are not dependent on each other. It is designed that way. Whereas, when you consider languages like C# and Java you cannot have access specifier narrowed down ( i.e. stricter access specifier ) when compared to base class. So, the code does not even compile in those languages. Since there is no such restriction in C++, the code compiles.

That is the reason why it is actually advised not to make virtual function public. So, make your non-virtual methods public and make them act as interface methods .
Make your virtual methods protected or private ( depending on the accessibility you desire ) and call those virtual methods from the non-virtual methods.

No comments:

Post a Comment

AWS Data Pipeline Services

https://www.youtube.com/watch?v=tykcCf-Zz1M