0

I am able to access function which is under protected access specifier in the given code.can u explain how it works?

#include <iostream> using namespace std; class kittu{ public: virtual void fun() { cout<<"hello"<<endl; } }; class lucky:public kittu{ protected: void fun() { cout<<"i am lucky"<<endl; } }; int main() { lucky l; kittu *k=&l; k ->fun(); return 0; }

22nd Jun 2018, 4:32 PM
S.Krishnama Naidu
1 ответ
+ 3
When you have kittu *k = &l; Your base class pointer points to an object of the derived class. k->fun(); Invoking a call to fun() will first get the compiler to check if there is a fun() method inside the base class, and if the method is accessible inside the base class. fun() happens to exist and is accessible inside the base class. No problems. The program proceeds to decide which fun() method to invoke, since fun() is declared to be virtual. The object pointed to by the base class pointer belongs to the derived class, so the program invokes the fun() method inside the derived class.
22nd Jun 2018, 5:13 PM
Hatsy Rei
Hatsy Rei - avatar