Function Overloading Vs Function Overriding in C++

Function Overloading means having multiple definitions of the function by changing its signature.

float area(int a);
float area(int a, int b); 

Function Overriding means redefining a base class function in its derived class with same signature i.e return type and parameters.

 // CPP program to illustrate 
 // concept of function overriding, runtime polymorphism

    #include <iostream> 
    using namespace std; 

    class base { 
    public: 
        virtual void print() 
        { 
            cout << "print base class" << endl; 
        } 

        void show() 
        { 
            cout << "show base class" << endl; 
        } 
    }; 

    class derived : public base { 
    public: 
        void print() 
        { 
            cout << "print derived class" << endl; 
        } 

        void show() 
        { 
            cout << "show derived class" << endl; 
        } 
    }; 

    int main() 
    { 
        base* bptr; 
        derived d; 
        bptr = &d; 

        // virtual function, binded at runtime 
        bptr->print(); 

        // Non-virtual function, binded at compilation time 
        bptr->show(); 
    } 
  1. Inheritance: For Overriding of functions we must inherit  one class is from another class. Overloading its not necessary.
  2. Function Signature: Overloaded functions differs in function signature but in overriding, function signatures must be same.
  3. Scope of functions: Overridden functions are in different scopes; whereas overloaded functions are in same scope.
  4. Behavior of functions: Overriding is needed when derived class function has to do some added or different job than the base class function. Overloading is used to have same name functions which behave differently depending upon parameters passed to them.

That's all now !!


No comments:

Post a Comment

Rendering 3D maps on the web using opesource javascript library Cesium

This is a simple 3D viewer using the Cesium javascript library. The example code can be found here . Click on question-mark symbol on upp...