Michael
Michael

Reputation: 3239

How to access member function without using the member.functionName syntax c++?

I am trying to access a member function of my Fraction class called "compare" which takes 2 parameters, both Fraction objects. Why is it that the only way I can call the compare function is through a member of the Fraction class? For example, I have the following code:

bool operator==(Fraction a, Fraction b) {
    if (compare(a, b) < 0) {  // this line gives an error during compilation
        // Do stuff
    }
    return true;
}

int Fraction::compare(Fraction a, Fraction b) {
    // do stuff
    return 0;
}

The error given at the line where compare is called, and it gives the following message:

..\fraction.cpp:107:18: error: 'compare' was not declared in this scope

If I change that line to the following, it works.

if (a.compare(a, b) < 0) {

It seems redundant that the only way to call compare is by doing a.compare, when a is an input parameter to the function anyway. I understand I can get out of this by making the operator overload function a friend function but I am being asked to implement it as a non-member function.

Is there a way to make this function static like in Java where I can just call Fraction.compare(a, b), or is this not possible in C++11?

Thanks for the help in advance.

Upvotes: 1

Views: 112

Answers (1)

Andreas DM
Andreas DM

Reputation: 11008

Well, you could declare the method static and access it through operator ::
Ex:

class Fraction {
public:
    static bool compare(int a, int b);
};

bool Fraction::compare(int a, int b)
{
    return a > b;
}

int main()
{
    cout << boolalpha << Fraction::compare(5, 4) << '\n';
}

Upvotes: 4

Related Questions