I was writing a program of function overloading in Visual C++ 2010 .
Following is my code
// overload.cpp : Defines the entry point for the console application.
#include<Windows.h>
#include<iostream>
#include<conio.h>
using namespace std;
//abs is overloaded in 3 types
int abs(int i);
double abs(double d);
long abs(long f);
void main()
{
cout<<abs(-10)<<"\n";
cout<<abs(-11.0)<<"\n";
cout<<abs(-9L)<<"\n";
getch();
}
int abs(int i)
{
cout<<"using integer abs()\n";
return i>0? -i:i;
}
double abs(double d)
{
cout<<"using double abs()\n";
return d>0? -d:d;
}
long abs (long l)
{
cout<<"using long abs()\n";
return l>0?-l:l;
}
I am having problems in double abs and long abs function that
1>c:\users\abc\documents\visual studio 2010\projects\overload\overload\overload.cpp(22): error C2084: function 'double abs(double)' already has a body
1>c:\users\abc\documents\visual studio 2010\projects\overload\overload\overload.cpp(26): error C2084: function 'long abs(long)' already has a body
Why this problem is coming?
I have changed the compilation from c to c++
but recently I ran an other program for overloading,it worked.I don't know how? here is the code.
#include<iostream>
#include<cstdio>
#include<conio.h>
#include<cstring>
using namespace std;
void stradd(char*s1,char*s2);
void stradd(char*s1,int i);
void main()
{
char str[80];
strcpy(str,"hello");
stradd(str,"there");
cout<<str<<"\n";
getch();
}
//concatenate a string with a "stringized "integer
void stradd(char*s1,int i)
{
char temp[80];
sprintf(temp,"%d",i);
strcat(s1,temp);
}
//concatenate 2 strings
void stradd(char*s1,char *s2)
{
strcat(s1,s2);
}
and output is hellothere
Your problem comes from a header in which abs is declared for some types such as double. You're not allowed to have to functions with exactly the same header (that is, same return type, same name, same list of parameters, same qualifiers such as const).
There are two ways of avoiding this:
Use the standard library: std::abs is good, you don't need to implement it yourself
Naming the method absoluteValue or myAbs or whatever you like, but not abs
A third way, namely removing using namespace std does not work according to your comment. This is because you include Windows.h. This itself includes a bunch of headers, probably including math.h. This gives a method called abs in the global namespace. Better don't include Windows.h and include cmath if you need to. Then, abs is only declared in namespace std, hence you can call it with std::abs and is different from abs.
When overload resolution cannot select one function as the unique best match, the call is ambiguous. An ambiguous call produces a compilation error.
In std there is already an abs() with the following signature:
int abs (int n);
So while you try to overload it with double and long it results in ambiguity for the compiler.
If you're a beginner learning about coding i suggest you to use function names not defined in libraries (at least the ones you have included).
stefan have already given the solution to it:
Remove using namespace std; and explicitly write std::cout
OR
Re name your function to absoluteValue or something else
OR
Use explicit namespaces in function declaration and calls. (Not tested, though it should work)
Put your function inside a class or namespace.
Maybe this would provide you with a little insight (From SO).
EDIT:
The second question's overloaded functions stradd() is not defined in any other library. That is why no Compilation Errors. The following function signature in your code will result an error: char * strcat ( char * destination, const char * source )
Your primary problem is that you use global namespace. Just declare your function in your own namespace and all name collisions will be gone.
Let me explain why you're getting those compile-time errors.
Somewhere in the headers you included there are double abs(double) and long abs(long) functions. Then you're creating functions with the same signatures by your own. So compiler just don't know what to use when you'll call one of them - there are 2 pairs of equal functions. So it refuses to compile that, and you're getting those errors.
So you have 2 choices - hope that every time you'll want to create a function you will choose an unique name, or just create a namespace and your function names should be unique only to another functions in your namespace.
And it's not about overloading - void func(int i) overloads void func(float f), but void func(int i) overrides void func(int i). You can override superclass member functions in subclasses, but you cannot override standalone functions like abs().
just change abs function name with another.
abs() is a keyword therefore it is showing errors.
Related
we have following code in legacy and use this place hundread of place. I am compiling code with c++11 and got following error. I can understand issue(saw couple of question on stackoverflow) as abs support int/long int in C++11.
Is there any way to avoid 100 place and replace abs with fabs. Can I update such a way if it can handle both version. any input.
call of overloaded ‘abs(double&)’ is ambiguous
double abs(double d)
{
return (d < 0 ? -d : d);
}
Why redefine what is already defined?
You can find the function that you want in the header <cmath>.
Further reading on c++ reference.
#include <cmath>
add this header file and try to use abs() built-in function and see that work or not.
This error is present when compiling against Visual C++ 2003 through 2013. It is not present when compiling against g++ 4.9.2.
#include <ios>
int main() {
left(*(new std::string));
return 0;
}
The problem is that it reports some some error about the arguments. The result I expect is for it to say "identifier not found" because std::left() should be out of scope!
Example of copied inline function:
STD_BEGIN
inline std::ios_base& __CLRCALL_OR_CDECL left2(std::ios_base& _Iosbase) {
_Iosbase.setf(std::ios_base::left, std::ios_base::adjustfield);
return (_Iosbase);
}
_STD_END
I examined ios and found that it's an inline function. I copied it out, stuck it into the std namespace using the same macros, and gave it a new name. But the new function is out of scope?
So why is std::left() and std::right() in scope here?
Argument dependent lookup will consider function overloads in a namespace, if one or more arguments have a type that's also in that namespace. In this case, the argument type is std::string, so namespace std is considered when looking for overloads, and std::left is found.
By the way, never write *new in real code; it almost invariably causes a memory leak.
What's wrong with this one? The compiler says: Declaration syntax error.
Source File:
#include<iostream>
using namespace std;
int main(int argc, char **argv) {
void printBinary(const unsigned char val) {
//printBinary() func. outputs byte in binary
for(int i=7;i>=0;i--)
if(val & (1<<i)) //generates a single bit with offset position
std::cout<<"1";
else
std::cout<<"0"
}
return 0;
}///:~
Header file:
void printBinary(const unsigned char val);
///:~
You are trying to define one function inside another function. This is illegal. Why did you place the definition of printBinary into the body of main?
Aside from the lambda functions in C++11, C++ has no such feature as local functions. All functions "live" in namespace scope.
The only workaround for this rule is inline member function definitions for local classes, although it does not produce a local function either.
You can't define a function in another function's (in this case, main) body.
//EDIT: Unless, of course, it's lambda.
This is a small program :
#include <iostream>
using namespace std;
int main() {
f();
system("pause");
}
void f() {
static int x = 20 ;
class tester {
public :
tester() {
cout << x ;
}
} x1;
}
The error that i get here is :error C3861: 'f': identifier not found
If i place the function f above main I will get the desired output.
Why it is so ?
I was told that program execution begins at main. According to this the code should run in the first case also.
How does the compiler start reading the program?
The beginning of the compilation and the beginning of the execution of the program are two different things.
The execution starts from the main.
The compilation begins from the beginning of the file; the compiler don't "jump around" the file to find the needed pieces, but it reads the input in a linear fashion (I suspect that this related, among the other things, to the fact that the C++ grammar is really complicated).
When the compiler is at some point in parsing the file, it only knows what has been declared/defined up to that point1.
Because of this, function prototypes (and non-defining declarations in general) have been invented: the prototypes of all the functions defined in the file are put at the beginning of the file, typically after the #include directives or in a separated include file. The prototypes tell to the compiler that such functions will be defined later, and what is the function signature (i.e. name, parameters, return value).
The prototype is made as a normal function, but without the body, which is replaced by a semicolon2. For example, in your code you would write
void f();
before the main.
IIRC there are some relaxations to this rule that allow the compiler to "wait" for some declarations to make some template magic work, but this is not relevant here.
In a prototype is also common not to write the names of the parameters, leaving just their type (this can be done also in function definitions, but it doesn't make much sense there unless you have a formal parameter you don't use). Still, I prefer to leave the parameter names there as a form of documentation.
I was told that program execution begins at main.
And that's exactly the point.
The compiler starts from main, and then sees a call to f(), which it has not encountered so far (as it is defined afterwards), so it does not know what to do with it.
If you want to define f after main you can place a function prototype before, such as
#include <iostream>
using namespace std;
void f(); // <--- This tells the compiler that a function name f will be defined
int main() {
f();
system("pause");
}
void f() {
static int x = 20 ;
class tester {
public :
tester() {
cout << x ;
}
} x1;
}
To be able to call a function it must have been declared at some earlier point in the code. This is just a rule of the language designed to help compilers.
You can declare the function earlier with e.g.
void f();
...and then define it after main as you have done.
The compiler starts at the top and reads down to the bottom.
you'll need to have something like:
#include <iostream>
using namespace std;
void f();
int main() {
f();
system("pause");
}
void f() {
static int x = 20 ;
class tester {
public :
tester() {
cout << x ;
}
} x1;
}
No, the compiler needs to see at least a declaration of f() before it is used. A c(++) code file is a simple text file and must be read from begin to end by the compiler.
During the compilation process, when the compiler is evaluating main() it needs to know what f() is in advance to be able to generate the correct assembly code to call this function. That's why you need to put it before main() in this case.
As an alternative you can declare the prototype of f() before main() so the compiler knows it's a local function declared somewhere else on your file:
void f(); // prototype
int main()
{
// .. code ..
}
void f() // implementation of f()
{
// .. code ..
}
I have a function called:
void initializeJSP(string Experiment)
And in my MyJSP.h file I have:
2: void initializeJSP(string Experiment);
And when I compile I get this error:
MyJSP.h:2 error: variable or field initializeJSP declared void
Where is the problem?
It for example happens in this case here:
void initializeJSP(unknownType Experiment);
Try using std::string instead of just string (and include the <string> header). C++ Standard library classes are within the namespace std::.
This is not actually a problem with the function being "void", but a problem with the function parameters. I think it's just g++ giving an unhelpful error message.
EDIT: As in the accepted answer, the fix is to use std::string instead of just string.
or like in my case the solution was just to declare the fitting header in the main.cpp instead of the header in the function.cpp, trying to include that one..
...
#include"header.h" //instead of "function.cpp"
int main()
and in function.cpp
#include"header.h"
void ()
this way compiling and linking just works fine ...
The thing is that, when you call a function you should not write the type of the function, that means you should call the funnction just like
initializeJSP(Experiment);
Other answers have given very accurate responses and I am not completely sure what exactly was your problem(if it was just due to unknown type in your program then you would have gotten many more clear cut errors along with the one you mentioned) but to add on further information this error is also raised if we add the function type as void while calling the function as you can see further below:
#include<iostream>
#include<vector>
#include<utility>
#include<map>
using namespace std;
void fun(int x);
main()
{
int q=9;
void fun(q); //line no 10
}
void fun(int x)
{
if (x==9)
cout<<"yes";
else
cout<<"no";
}
Error:
C:\Users\ACER\Documents\C++ programs\exp1.cpp|10|error: variable or field 'fun' declared void|
||=== Build failed: 1 error(s), 0 warning(s) (0 minute(s), 0 second(s)) ===|
So as we can see from this example this reason can also result in "variable or field declared void" error.
Did you put void while calling your function?
For example:
void something(int x){
logic..
}
int main() {
**void** something();
return 0;
}
If so, you should delete the last void.