Differentiate between function overloading and function overriding

前端 未结 11 1834
臣服心动
臣服心动 2020-11-29 18:40

Differentiate between function overloading and function overriding in C++?

相关标签:
11条回答
  • 2020-11-29 19:06

    Function overloading is done when you want to have the same function with different parameters

    void Print(string s);//Print string
    void Print(int i);//Print integer
    

    Function overriding is done to give a different meaning to the function in the base class

    class Stream//A stream of bytes
    {
    public virtual void Read();//read bytes
    }
    
    class FileStream:Stream//derived class
    {
    public override void Read();//read bytes from a file
    }
    class NetworkStream:Stream//derived class
    {
    public override void Read();//read bytes from a network
    }
    
    0 讨论(0)
  • 2020-11-29 19:10

    Function overloading is same name function but different arguments. Function over riding means same name function and same as arguments

    0 讨论(0)
  • 2020-11-29 19:11

    Overriding means, giving a different definition of an existing function with same parameters, and overloading means adding a different definition of an existing function with different parameters.

    Example:

    #include <iostream>
    
    class base{
        public:
        //this needs to be virtual to be overridden in derived class
        virtual void show(){std::cout<<"I am base";}
        //this is overloaded function of the previous one
        void show(int x){std::cout<<"\nI am overloaded";} 
    };
    
    class derived:public base{
        public:
        //the base version of this function is being overridden
        void show(){std::cout<<"I am derived (overridden)";}
    };
    
    
    int main(){
        base* b;
        derived d;
        b=&d;
        b->show();  //this will call the derived overriden version
        b->show(6); // this will call the base overloaded function
    }
    

    Output:

    I am derived (overridden)
    I am overloaded
    
    0 讨论(0)
  • 2020-11-29 19:11

    in overloading function with same name having different parameters whereas in overridding function having same name as well as same parameters replace the base class to the derived class (inherited class)

    0 讨论(0)
  • 2020-11-29 19:12

    You are putting in place an overloading when you change the original types for the arguments in the signature of a method.

    You are putting in place an overriding when you change the original Implementation of a method in a derived class.

    0 讨论(0)
提交回复
热议问题