इस खंड में हम C++ में डेराइव्ड क्लास मेथड्स के प्रतिबंधित एक्सेस के बारे में दिलचस्प तथ्यों पर चर्चा करेंगे। हम कुछ उदाहरण देखेंगे और आउटपुट का विश्लेषण करके C++ में डेराइव्ड क्लास मेथड्स के उपयोग के प्रतिबंधों के बारे में अधिक जानेंगे।
उदाहरण (C++)
बेहतर समझ के लिए निम्न कार्यान्वयन देखें:
#include <iostream> using namespace std; class BaseClass { public: virtual void display(){ cout << "Print function from the base class" << endl; } }; class DerivedClass: public BaseClass { private: void display() { cout << "Print function from the derived class" << endl; } }; int main() { } यह ठीक है, अब यदि हम मेन फंक्शन ब्लॉक को इससे बदलते हैं, तो हमें नीचे जैसी त्रुटि मिलेगी:
int main() { DerivedClass d; d.display(); } आउटपुट
main.cpp: In function 'int main()': main.cpp:20:15: error: 'virtual void DerivedClass::display()' is private within this context d.display(); ^ main.cpp:13:10: note: declared private here void display() { ^~~~~~~ यह त्रुटि दिखाता है क्योंकि डेराइव्ड क्लास में मेथड प्राइवेट है। अब इस कार्यान्वयन को देखें, जहां फंक्शन को बेस पॉइंटर का उपयोग करके कॉल किया जाता है। यह फंक्शन को कॉल कर सकता है।
उदाहरण (C++)
#include <iostream> using namespace std; class BaseClass { public: virtual void display(){ cout << "Print function from the base class" << endl; } }; class DerivedClass: public BaseClass { private: void display() { cout << "Print function from the derived class" << endl; } }; int main() { BaseClass *b = new DerivedClass; b->display(); } आउटपुट
Print function from the derived class
उपरोक्त प्रोग्राम से, हम देख सकते हैं कि डेराइव्ड क्लास का प्राइवेट फंक्शन DerivedClass::display() बेस क्लास पॉइंटर के माध्यम से कॉल किया जा रहा है, प्रोग्राम ठीक काम करता है क्योंकि display() फंक्शन बेस क्लास में पब्लिक है। एक्सेस स्पेसिफायर्स को कंपाइल टाइम पर वेरिफाई किया जाता है और display() बेस क्लास में पब्लिक है। रन टाइम के दौरान, केवल पॉइंटेड ऑब्जेक्ट से संबंधित फंक्शन कॉल किया जाता है और एक्सेस स्पेसिफायर वेरिफाई नहीं किया जाता। इसलिए डेराइव्ड क्लास का एक प्राइवेट फंक्शन बेस क्लास के पॉइंटर के माध्यम से कॉल किया जा रहा है।