Just wondering how the compiler knows the correct operator method to call.
Code:
#include <iostream>
class COUNTER {
public:
COUNTER();
~COUNTER();
int get_val() const;
void set_val(int x);
const COUNTER& operator ++();
const COUNTER operator ++(int flag);
const COUNTER& operator --();
const COUNTER operator --(int flag);
private:
int val;
};
COUNTER::COUNTER(): val(0) {}
COUNTER::~COUNTER() {}
//methods
int COUNTER::get_val() const { return val; }
void COUNTER::set_val(int x) { val = x; }
//overloaded operators
const COUNTER& COUNTER::operator ++() {
++val;
return *this;
}
const COUNTER COUNTER::operator ++(int flag) {
COUNTER temp(*this);
++val;
return temp;
}
const COUNTER& COUNTER::operator --() {
--val;
return *this;
}
const COUNTER COUNTER::operator --(int flag) {
COUNTER temp(*this);
--val;
return temp;
}
int main (void) {
using namespace std;
COUNTER i,j;
cout << endl;
cout << "COUNTER i,j starting values" << endl;
cout << "i == " << i.get_val() << endl;
cout << "j == " << j.get_val() << endl;
cout << endl;
cout << "j = ++i" << endl;
j = ++i;
cout << "++i == " << i.get_val() << endl;
cout << "j == " << j.get_val() << endl;
cout << endl;
cout << "j = i++" << endl;
j = i++;
cout << "i++ == " << i.get_val() << endl;
cout << "j == " << j.get_val() << endl;
cout << endl;
i.set_val(5);
j.set_val(5);
cout << "Reset COUNTER i,j" << endl;
cout << "i == " << i.get_val() << endl;
cout << "j == " << j.get_val() << endl;
cout << endl;
cout << "j = --i" << endl;
j = -- i;
cout << "i == " << i.get_val() << endl;
cout << "j == " << j.get_val() << endl;
cout << endl;
cout << "j = i--" << endl;
j = i--;
cout << "i == " << i.get_val() << endl;
cout << "j == " << j.get_val() << endl;
cout << endl;
return 0;
}
Without accually changing the body of the methods and just swapping the flags in the declaration and definition the result is not correct. Does the compiler just look for the flag and say without a doubt this is the postfix operator or is it more involved?