Home > OS >  Why do I get "functions that differ only by return type cant't be overloaded" error w
Why do I get "functions that differ only by return type cant't be overloaded" error w

Time:03-13

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.

CodePudding user response:

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;
}
  • Related