FAQ 29.01 What is the difference between overloaded functions and overridden functions?

Overloading has the same scope, same name, different signatures, and virtual is not required. Overriding has different scopes, same name, same signatures, and virtual is required.

The term signature designates the combination of a function's name, the types and order of its parameters, and, if the function is a nonstatic member function, its const and/or volatile qualifiers.

Overloading occurs when two or more functions are in the same scope (for example, both in the same class or both at namespace scope) and have the same name but different signatures. Overriding occurs when a class and one of its derived classes both define a member function with the same signature and the member function is declared to be virtual in the base class.

In the following example, Base::f(int) and Base::f(float) overload each other, while Derived::g() overrides Base::g().

 #include <iostream> using namespace std; class Base { public:   virtual ~Base()         throw();   virtual void f(int x)   throw();   virtual void f(float x) throw();   virtual void g()        throw(); }; Base::~Base() throw()   { } void Base::f(int x) throw()   { cout << "Base::f(int)\n"; } void Base::f(float x) throw()   { cout << "Base::f(float)\n"; } void Base::g() throw()   { cout << "Base::g()\n"; } class Derived : public Base { public:   virtual void g() throw(); }; void Derived::g() throw()   { cout << "Derived::g()\n"; } int main() {   Derived d;   Base* bp = &d;  // OK: Derived is kind-of Base   bp->f(42);   bp->f(3.14f);   bp->g(); } 

The output of this program follows.

 Base::f(int) Base::f(float) Derived::g() 


C++ FAQs
C Programming FAQs: Frequently Asked Questions
ISBN: 0201845199
EAN: 2147483647
Year: 2005
Pages: 566
Authors: Steve Summit

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net