954,480 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Overloaded Functions

I'm wondering what is the proper way to point at an overloaded function. Is it correct to cast the function to the proper type?

#include <iostream>

int double_it(int x)
{
	return x * 2;
}

int double_it(int x, int y)
{
	return (x + y) * 2;
}


int main(int argc, char**argv)
{
	void *myfunc = (void*)(int(*)(int))double_it;
	return 0;
}
gerard4143
Nearly a Posting Maven
2,272 posts since Jan 2008
Reputation Points: 512
Solved Threads: 387
 

I had just forgot about function pointers :D
Curious, I tried this and it worked.

#include <iostream>
using namespace std;

int fn(int a)
{
  cout << "Integer function called";
  return 0;
}

int fn(char a)
{
  cout << "Character function called";
  return 0;
}

int main()
{
  int (*fintptr)(int) = &fn;
  int (*fcharptr)(char) = &fn;
  fintptr(1);
  cout << "\n";
  fcharptr('a');
  cout << "\n";
}
nileshgr
Junior Poster
166 posts since Aug 2009
Reputation Points: 17
Solved Threads: 23
 

So the code posted below is proper.

#include <iostream>

typedef int(*pfunc1)(int);
typedef int(*pfunc2)(int, int);

int double_it(int x)
{
	return x * 2;
}

int double_it(int x, int y)
{
	return (x + y) * 2;
}


int main(int argc, char**argv)
{
	pfunc1 func_1 = double_it;
	pfunc2 func_2 = double_it;

	std::cout << func_1(123) << std::endl;
	std::cout << func_2(345, 567) << std::endl;
	return 0;
}
gerard4143
Nearly a Posting Maven
2,272 posts since Jan 2008
Reputation Points: 512
Solved Threads: 387
 

Seems to be. If the compiler doesn't complain, its fine :)
That's my way of doing things :D

nileshgr
Junior Poster
166 posts since Aug 2009
Reputation Points: 17
Solved Threads: 23
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You