Search code examples
c++functionoverloading

make prototype of overloading function c++


I want to make a overloading function with a prototype in C++.

#include <iostream>

using namespace std;

int rectangle(int p, int l);

int main() {
    cout << rectangle(3);
    return 0;
}

int rectangle(int p) {
    return p*p;
}

int rectangle(int p, int l) {
    return p*l;
}

I got error at

int rectangle(int p, int l);

is that possible make prototype with a overloading function? if possible how to do it


Solution

  • You've to declare the function before you use/call it. You did declare the 2 argument version of rectangle function but you seem to forget to declare the 1 argument taking version.

    As shown below if you add the declaration for the 1 argument version then your program works(compiles).

    #include <iostream>
    using namespace std;
    
    //declare the function before main
    int rectangle(int p, int l);
    int rectangle(int p);//ADDED THIS DECLARATION
    int main() {
        cout << rectangle(3);
        return 0;
    }
    //define the functions after main
    int rectangle(int p) {
        return p*p;
    }
    int rectangle(int p, int l) {
        return p*l;
    }
    
    

    The output of the program can be seen here.

    Alternative solution:

    If you don't want to declare each function separately then you should just define them before main instead of declaring them as shown below.

    #include <iostream>
    using namespace std;
    
    //define the functions before main. This way there is no need to write a separate function declaration because all definition are declarations
    int rectangle(int p) {
        return p*p;
    }
    int rectangle(int p, int l) {
        return p*l;
    }
    
    int main() {
        cout << rectangle(3);
        return 0;
    }