Function Overloading in C++

    Function overloading (फंक्शन ओवरलोडिंग) object oriented programming(ऑब्जेक्ट ओरिएंटेड प्रोग्रामिंग) की एक विशेषता है जहां दो या दो से अधिक Function का एक ही नाम के हो सकते है लेकिन अलग-अलग parameters होंगे।

    जब किसी function का नाम विभिन्न jobs के साथ Function हो जाता है तो इसे Function overloading (फंक्शन ओवरलोडिंग) कहा जाता है।

    Function overloading (फंक्शन ओवरलोडिंग) में "Function " नाम समान होना चाहिए और arguments अलग-अलग होने चाहिए।

    Function overloading (फंक्शन ओवरलोडिंग) को C++ में polymorphism(पॉलीमॉर्फिज्म) feature का एक उदाहरण माना जा सकता है।

    Function overloading (फंक्शन ओवरलोडिंग) का advantage यह है कि यह प्रोग्राम की readability को बढ़ाता है क्योंकि आपको some action के लिए अलग-अलग नामों का उपयोग करने की आवश्यकता नहीं होती है।

    C++ Function Overloading Example

    Function overloading (फंक्शन ओवरलोडिंग) को demonstrate करने के लिए एक सरल C++ उदाहरण निम्नलिखित है।

    Example #01:-


        #include <iostream>
        using namespace std;

        void print(int i) {
        cout << " Here is int " << i << endl;
        }
        void print(double f) {
        cout << " Here is float " << f << endl;
        }
        void print(char const *c) {
        cout << " Here is char* " << c << endl;
        }

        int main() {
        print(10);
        print(10.10);
        print("ten");
        return 0;
        }

    Output:-

    Here is int 10
    Here is float 10.1
    Here is char* ten

    Example #02:-


        // program of function overloading when number of arguments vary.
        #include <iostream>
        using namespace std;
        class Cal
        {
        public:
            static int add(int a, int b)
            {
                return a + b;
            }
            static int add(int a, int b, int c)
            {
                return a + b + c;
            }
        };
        int main(void)
        {
            Cal C; //     class object declaration.
            cout << C.add(10, 20) << endl;
            cout << C.add(12, 20, 23);
            return 0;
        }

    Output:-

    30
    55


    Example #03:-


        // Program of function overloading with different types of arguments.
        #include <iostream>
        using namespace std;
        int mul(int, int);
        float mul(float, int);

        int mul(int a, int b)
        {
            return a * b;
        }
        float mul(double x, int y)
        {
            return x * y;
        }
        int main()
        {
            int r1 = mul(6, 7);
            float r2 = mul(0.2, 3);
            std::cout << "r1 is : " << r1 << std::endl;
            std::cout << "r2 is : " << r2 << std::endl;
            return 0;
        }

    Output:-

    r1 is : 42 
    r2 is : 0.6

    Post a Comment

    0 Comments