Expand|Select|Wrap|Line Numbers
- #include <iostream>
- using namespace std;
- class Square
- {
- public:
- Square();
- Square(int side);
- int GetSide() {return *itsSide;}
- Square & operator= (Square & rhs);
- const Square & operator++ (); //WHY IS THIS CONST?
- const Square operator++ (int); //WHY IS THIS CONST?
- private:
- int * itsSide; //pointer to int
- };
- //default constructor
- Square::Square()
- {
- itsSide = new int(10); //Assigns new memory on heap for the calling
- //object and assigns 10
- }
- //overloaded constructor
- Square::Square(int side)
- {
- itsSide = new int(side);//Assigns new memory on heap for the calling
- //object and assigns the passed in parameter
- }
- //overloaded assignment operator
- Square & Square::operator= (Square & rhs)
- {
- delete itsSide; //WHY IS IT DELETING THE CURRENT MEMORY ADDRESS
- //THAT THE POINTER POINTS TO?
- itsSide = new int; //Assigning new address to pointer
- *itsSide = rhs.GetSide(); //get the value for the crate object
- //and assign to the new address
- return *this; //WHAT IS BEING RETURNED HERE?
- }
- const Square & Square::operator++ ()
- {
- ++(itsSide); //WHY IS THIS BEING INCREMENTED WITHOUT BEING DEREFERENCED?
- return *this; //WHERE DOES THIS VALUE GET RETURNED TO?
- }
- const Square Square::operator++ (int)
- {
- Square temp(*this); //dereference address being passed in
- //and assign value to temp
- ++(itsSide); //WHY IS THIS BEING INCREMENTED WITHOUT BEING DEREFERENCED?
- return temp; //WHERE DOES THIS VALUE GET RETURNED TO?
- }
- int main()
- {
- Square box; //default constructor called
- Square crate(100); //overloaded constructor called
- cout << box.GetSide() << endl; //output
- cout << crate.GetSide() << endl; //output
- box = crate; //overloaded assignment operator called
- cout << box.GetSide() << endl; //output
- crate++; //Overloaded postfix operator
- cout << crate.GetSide()<< endl; //WHY IS THIS RETURNING 4064624?
- system("pause");
- return 0;
- }