Im learning about postfix and prefix operators and how to overload them. I've created my class with overloaded pre and post fix operators how ever when used in the main program the results aren't what I expected.
The program creates a simple shape from a class that has default constructor, destructor, an overloaded constructor, copy constructor, accessors methods for member variable itsRadius of Get and Set and my overloaded operators prefix, postfix and assignment (assignment works fine)
The main section of the program creates two objects. One uses the default constructor value of "5" and the other is set using the overloaded constructor with the value "9".
They are both printed.
The prefix and post fix operators are used tehn the values are printed again with unexpected results
//Main program
int _tmain(int argc, _TCHAR* argv[])
{
SimpleC c1;
SimpleC c2(9);
cout << "C1 Radius: " << c1.GetRadius() << endl;
cout << "C2 Radius: " << c2.GetRadius() << endl;
c1++;
++c2;
cout << "C1 Radius: " << c1.GetRadius() << endl;
cout << "C2 Radius: " << c2.GetRadius() << endl;
system ("pause");
return 0;
}
//Class definition
class SimpleC
{
public:
SimpleC();
SimpleC(int);
SimpleC(const SimpleC&); //Copy
~SimpleC();
//Overloading operators
const SimpleC& operator++ (); //Prefix
const SimpleC operator++ (int); //Postfix
SimpleC& operator=(const SimpleC&); //Assignment
//Accessor functions
void SetRadius(int);
int GetRadius() const;
private:
int *itsRadius;
};
//Class member function declarations
//Prefix, increment then fetch
const SimpleC& SimpleC::operator++()
{
++(itsRadius);
return *this;
}
//Postfix, creates temp to store original, increment, then fetch
const SimpleC SimpleC::operator++(int)
{
SimpleC temp(*this);
++(itsRadius);
return temp;
}
RESULT
C1 Radius: 5
C1 Radius: 9
C1 Radius: -33686019
C1 Radius: -33686019
I have omitted some of the code to save space and to save confusion if any more is needed please let me know.
I would be helpful and very appreciated if anyone could point where I'm going wrong
Thanks in advance