Life Beyond Code

Why doesn’t overloading work for derived classes?

Posted on: January 8, 2007

Today i was reading an Interview of Bjrane Stroustrup. This document clears on of my confusion about overloading in C++. Copy of that text is below.

That question (in many variations) are usually prompted by an example like this:

#include<iostream>
 using namespace std;
class B {
      public:
        int f(int i) { cout << "f(int): "; return i+1; }
     }; 
class D : public B {
      public:
       double f(double d) { cout << "f(double): "; return d+1.3; }
        // ...
     };
int main()
    {
    D* pd = new D;
    cout << pd->f(2) << '\n';
    cout << pd->f(2.3) << '\n';
    }

which will produce:

	f(double): 3.3
 	 f(double): 3.6

rather than the

	f(int): 3
	 f(double): 3.6

that some people (wrongly) guessed.

In other words, there is no overload resolution between D and B. The compiler looks into the scope of D, finds the single function “double f(double)” and calls it. It never bothers with the (enclosing) scope of B. In C++, there is no overloading across scopes – derived class scopes are not an exception to this general rule. (See D&E or TC++PL3 for details).

But what if I want to create an overload set of all my f() functions from my base and derived class? That’s easily done using a using-declaration:

class D : public B {
       public:
	using B::f;	// make every f from B available
	double f(double d) { cout << "f(double): "; return d+1.3; }
		// ...
     };

Give that modification, the output will be

	f(int): 3
	 f(double): 3.6

That is, overload resolution was applied to B’s f() and D’s f() to select the most appropriate f() to call

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Calendar

January 2007
M T W T F S S
« Sep   Feb »
1234567
891011121314
15161718192021
22232425262728
293031  

My del.icio.us

RSS Readings

  • An error has occurred; the feed is probably down. Try again later.

And Here is ME...

Top Clicks

  • None
%d bloggers like this: