I want to overload the ++ operator but it isn't working. The example I found in the book I'm using used stack memory allocation and I tried to do it through heap memory allocation. It isn't crashing but it isn't incrementing either.
I tried returning the pointer, making a reference, all sorts of stuff that I don't quite understand yet and nothing really worked.
#include <iostream>
using namespace std;
class MyObject{
public:
MyObject(int initVal = 0):value(initVal){cout << "Constructor called..." << endl;}
~MyObject(){cout << "Destructor called..." << endl;}
const MyObject& operator++();
int getValue(){return value;}
private:
int value = 0;
};
int main(){
int initVal = 0;
char done = 'N';
cout << "initVal?" << endl;
cin >> initVal;
MyObject *obj = new MyObject(initVal);
while(done == 'N'){
cout << "Current value of obj :" << obj->getValue() << ". Want to stop? (Y/N)" << endl;
cin >> done;
//cout << "value of done :" << done << endl;
//cin.get();
if(done != 'Y' || done != 'N'){
continue;
}
*obj++;
}
cout << "";
cin.get();
}
const MyObject& MyObject::operator++(){
cout << "OVERLOADER CALLED val:" << value << endl;
value++;
return *this;
}
Actual:
initVal?
10
Constructor called...
Current value of obj :10. Want to stop? (Y/N)
N
Current value of obj :10. Want to stop? (Y/N)
N
Current value of obj :10. Want to stop? (Y/N)
N
Current value of obj :10. Want to stop? (Y/N)
Expected:initVal?
10
Constructor called...
Current value of obj :10. Want to stop? (Y/N)
N
Current value of obj :11. Want to stop? (Y/N)
N
Current value of obj :12. Want to stop? (Y/N)
N
Current value of obj :13. Want to stop? (Y/N)
Y
Also, my test to see if the response was not either Y or N stops the program when true instead of iterating at the beginning of the while loop. Help on that is also appreciated.