Issue
I have following example of c++ code in visual studio 2022:
#include<iostream>
#include<string>
employee get_employee() {
employee out = { 1, "John"};
return out;
}
class employee {
public:
int id;
std::string name;
};
int main() {
std::cout << get_employee().name;
return 0;
}
But when I run it, I get compiler complaining about get_employee()
, specifically that "functions that differ only by return type cant't be overloaded".
But why does it do so, if I dont have another get_employee()
definition anywhere in my code?
I know that I can't create an instance of an class before I define the class itself, and moving get_employee()
definition below employee
class definition really solves the issue, but it doesn't explain why compiler says that "functions that differ only by return type cant't be overloaded" instead of saying that you "cant crate an istance of a class before defining the class itself", and I would like to know why.
Solution
The problem here is fairly simple. You're trying to use employee
before you've defined what it means. Move your definition of employee
before the definition of get_employee
.
#include<iostream>
#include<string>
class employee {
public:
int id;
std::string name;
};
employee get_employee() {
employee out = { 1, "John"};
return out;
}
int main() {
std::cout << get_employee().name;
return 0;
}
As to why the compiler gives a poor error message, my guess is that somehow or other the undefined name for the return type is tricking it into accepting the call to get_employee
as it would have in old C, where a function without a declaration is presumed to return type int
.
Then when it encounters the actual definition of get_employee
, it has one entry already saying get_employee
returns int
and takes no arguments, and now sees what it's thinking is an attempt at overloading that also takes no arguments, but returns a client
instead.
And that convinces it that what it's seeing is an attempt at overloading that uses the same parameter list (i.e., no parameters) but a different return type.
Answered By - Jerry Coffin Answer Checked By - Robin (PHPFixing Admin)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.