overloading vs overriding

后端 未结 4 1583
春和景丽
春和景丽 2021-01-02 02:00

I am a little confused over the two terminologies and would be glad to get some doubts clarified.

As I understand function overloading means having mult

4条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-02 02:20

    Function overloading is when you have several functions which differ in their parameter list or, if they are member functions, in their const/volatile qualification. (In some other languages you can also overload based on the return type, but C++ doesn't allow that.)
    Examples:

    void f(int);
    void f(char);
    
    class some_class {
      void g();
      void g() const;
    };
    

    Function overriding is when you redefine a base class function with the same signature. Usually this only makes sense if the base class function is virtual, because otherwise the function to be called (base or derived class' version) is determined at compile-time using a reference's/pointer's static type.
    Examples:

    class base {
      void f();
      virtual void g();
    };
    
    class derived : public base {
      void f();
      void g();
    };
    

    Function hiding is when you define a function ina derived class (or an inner scope) that has a different parameter list than a function with the same name declared in a base class (or outer scope). In this case the derived class' function(s) hides the base class function(s). You can avoid that by explicitly bringing the base class function(s) into the derived class' scope with a using declaration.
    Examples:

    class base {
      void f(int);
      void f(char);
    };
    
    class derived1 : public base {
      void f(double);
    };
    
    void f()
    {
      derived1 d;
      d.f(42); // calls derived1::f(double)!
    }
    
    class derived2 : public base {
      using base::f; // bring base class versions into derived2's scope
      void f(double);
    };
    
    void g()
    {
      derived2 d;
      d.f(42); // calls base::f(int)!
    }
    

    Just in case it's unclear: Based on these definitions, I'd call the scenario in question here overriding.

提交回复
热议问题