Function overloading. Help..

Feb 21, 2012 at 10:44pm
This code won't compile unless I gave the last two functions (which take char strings) different names. I tried finding what's wrong for an hour but couldnt...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#include<iostream>
using namespace std;
void print(int a)
{
	cout<<a<<endl;
}
void print(int b[],int sizeint)
{
	for(int i=0;i<sizeint;i++)
		cout<<b[i]<<" ";
	cout<<endl;
}
void print(int b[],int n,int m)
{
	for(int i=n;i<=m;i++)
		cout<<b[i]<<" ";
	cout<<endl;
}
void print(char ch[],int sizechar)
{
	for(int i=0;i<sizechar;i++)
		cout<<ch[i]<<" ";
	cout<<endl;
}
void print(char ch[],int n)
{
	for(int i=0;i<n;i++)
		cout<<ch[i]<<" ";
	cout<<endl;
}
void main()
{
	int a=555,sizeint=10,n=3,m=9,sizechar=5,endchar=2;
	int b[]={1,2,3,4,5,6,7,8,9,10};
	char ch[]={'a','b','c','d','e'};
	print(a);
	print(b,sizeint);
	print(b,n,m);
	print(ch,sizechar);
	print(ch,n);
}
Feb 21, 2012 at 10:49pm
That's because those two functions have the same parameters (char array and integer). The program wouldn't know which one to use.

Last edited on Feb 21, 2012 at 10:50pm
Feb 21, 2012 at 11:09pm
These two definitions are identical. Only the names of the second parameters are different.

1
2
3
4
5
6
7
8
9
10
11
12
void print(char ch[],int sizechar)
{
	for(int i=0;i<sizechar;i++)
		cout<<ch[i]<<" ";
	cout<<endl;
}
void print(char ch[],int n)
{
	for(int i=0;i<n;i++)
		cout<<ch[i]<<" ";
	cout<<endl;
}


So for the compiler these two functions have the same type

void ( char *, int )

and the same name print. I.e. the one definition rule is broken.
Topic archived. No new replies allowed.