C++ Method Overriding In Hindi

📔 : C++ 🔗

हम जानते हैं , कि Inheritance से हम किसी class को inherit करके उसकी properties और method को access या use में ले सकते हैं। लेकिन अगर कोई method पहले से base class में present है लेकिन फिर भी इसकी derived / child class में वो method define कर सकते हैं।


derived / child class में same name method को define करना Method Overriding कहलाता है।

C++ Method Overriding Example

CopyFullscreenClose FullscreenRun
#include <iostream>
using namespace std;
// define base class.
class A {
    public:
    void print() {
        cout << "A Class Function" << endl;
    }
};

// define B class that inherits A class.
class B : public A {
    public:
    // define same name method
    void print() {
        cout << "B Class Function" << endl;
    }
};

int main() {
    B oObj;
    oObj.print();
    return 0;
}
Output
B Class Function

Example में आप देख सकते हैं कि , print() name का same method दोनों classes में define किया गया है , और call करने पर B class काprint() method call हुआ है।

C++ call parent class method

तो जब भी child / derived class के object के साथ method call करेंगे तो compiler सबसे पहले child class में ही उस method को search करता है , और method execute होता है। हालाँकि अगर आप base / class के method को execute करना चाहते हैं तो आपको base / parent class का name लिखना पड़ेगा।

B oObj;
oObj.print();
oObj.A::print();

Output  : 

B Class Function
A Class Function

इसी तरह से अगर आप child / derived class में base / parent class की किसी property या method को access करना चाहते हैं तो simply base class के name को double colon :: के साथ access कर सकते हैं।
For Example :

CopyFullscreenClose FullscreenRun
#include <iostream>
using namespace std;
// define base class.
class A {
    public:
    void print() {
        cout << "A Class Function" << endl;
    }
};

// define B class that inherits A class.
class B : public A {
    public:
    void print() {
        // call base class method.
        A::print();
        cout << "B Class Function" << endl;
    }
};

int main() {
    B oObj;
    oObj.print();
    return 0;
}
Output
A Class Function
B Class Function

Related Topics :

Rahul Kumar

Rahul Kumar

Hi ! I'm Rahul Kumar Rajput founder of learnhindituts.com. I'm a software developer having more than 4 years of experience. I love to talk about programming as well as writing technical tutorials and blogs that can help to others. I'm here to help you navigate the coding cosmos and turn your ideas into reality, keep coding, keep learning :)

Get connected with me. :) LinkedIn Twitter Instagram Facebook

b2eprogrammers