Introduction for Method Overriding
Method Overriding ये Polymorphism का ही एक प्रकार है लेकिन Function Overloading से थोडासा अलग-अलग होने की वजह से उसे अलग से बनाया है |
जैसे Function Overloading में एक की नाम के member functions को अलग-अलग तरीके से बनाया जाता था, वैसे ही Function or Method Overriding में अलग -अलग classes में एक ही नाम के member functions को बनाया जाता है |
For Example,class A{ void show(){ ----------- } }; class B : public A{ void show(){ ----------- } };
Method Overriding में उन एक जैसे member functions की definition अलग-अलग होती है |
Method Overriding में Inheriatnce के लिए एक Base class और एक Derived class की जरुरत होती है |
Method Overriding के लिए एक जैसे member functions को एक ही class में नहीं लिखा जाता |
Method Overriding Early Binding का काम करता है |
Example for Method Overriding
Source Code :Output:#include <iostream.h> using namespace std; class A{ public: void show(){ cout << "class A"<<endl; } }; class B : public A{ public: void show(){ cout << "class B"<<endl; } }; int main(){ A a; B b; a.show(); //Early Binding b.show(); return 0; }
class A class B
Different type of Method Overriding
निचे दिया हुआ program कुछ अलग तरीके का है |
Program में हर एक class में दो-दो नाम के same member functions लिए है |
लेकिन display() ये member function दोनों class पर है | लेकिन एक में parameter नहीं है और एक में parameter है |
यहाँ पर Inheritance के नजरिये से class A का derived class B लिया है | इसकी वजह से Class A के जो members है, वो B class के object से भी access किये जा सकते है |
Program में B class में void display(int x) इस प्रकार से लिया है और A class में void display() ऐसा लिया है |
और आखिर में B class का object लेने की वजह से वो ज्यादा ध्यान अपने members की तरह देगा |
class A और class B में एक ही नाम का member function हो तो, जिस class के object के साथ दिया है उस data को access किया जाता है |
Program के आखिर में error आया है वो ये है कि, B class में display नाम का mamber function है, लेकिन वो paramter के साथ है | लेकिन उसे int main() में उसे parameter के साथ नहीं दिया |
Output:#include <iostream.h> using namespace std; class A{ public: void show(){ cout << "class A"<<endl; } void display(){ cout << "Base Class"<<endl; } }; class B : public A{ public: void show(){ cout << "class B"<<endl; } void display(int x){ int a = x; cout << "Value of a : "<<a<<endl; } }; int main(){ A a; B b; a.show(); //Early Binding b.show(); //b.display(); //No matching function for B class b.display(5); return 0; }
class A class B Value of a : 5