Project Home
Project Home
Source Code
Source Code
Documents
Documents
Wiki
Wiki
Discussion Forums
Discussions
Project Information
Project Info
Forum Topic - Problem with method overloading: (3 Items)
   
Problem with method overloading  
Why won't the following code compile?

=========================================

#include <stdio.h>

class Base {
public:
	virtual void Wibble( int i ) = 0;
	void Wibble( int *i ) {
		Wibble( *i );
	};
};

class Derived : public Base {
public:
	void Wibble( int i ) {
		printf( "%d ", i );
	} 
};

int main( int argc, char *argv[] ) {
	Derived der;
	int i = 10;
	der.Wibble( &i );
	return 0;
}

=========================================

I get two errors:
error: initializing argument 1 of 'virtual void Derived::Wibble(int)'
error: invalid conversion from 'int*' to 'int'

So it looks like the Derived class has not inherited the second overload of Wibble. Why not?

Two things fix it:
1) Rename the second overload to something like WibbleWobble. Then the compiler can find it OK.
2) An overload that does not involve a pointer seems to work OK. For example Wibble( float f )

Is there a switch I need to throw to make overloading work properly? Otherwise it looks like the compiler cannot cope 
with overloads involving pointers.

I am using Momentics 6.3.2 with GNU Compiler Collection (3.3.5).
Re: Problem with method overloading  
Hi,

It doesn't compile because it isn't valid C++.   You're running in to an example of http://www.parashift.com/c++-faq-
lite/strange-inheritance.html#faq-23.9 - Derived::Wibble(int) is hiding Base::Wibble(int*) (although you don't get the 
warning because it's a virtual function also declared on Base).

The FAQ describes the "technically correct" fix, which is to use a 'using' directive in the derived class.  
Unfortunately this is rather unsatisfying because you've got to do it in /every/ derived class, and IIRC it doesn't work
 in GCC 2.95.3 (although I can't recall where it went wrong).  The only alternatives are to change the name of the 
second invocation (call it, say, WibblePtr) or to use an external cover function to call the virtual function on your 
behalf. ie:

inline void DoWibble(Base& b, int i) { b.Wibble(i); };
inline void DoWibble(Base& b, int*i) { b.Wibble(*i); };

Sorry for the bad news,
-Will
Re: Problem with method overloading  
How very weird. I had no idea such a problem even exists. Anyway, the "using" solution solves the problem, so thanks for
 the help.