Differentiate between function overloading and function overriding

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

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

11条回答
  •  Happy的楠姐
    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 
    
    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
    

提交回复
热议问题