My goal is to create two objects, use the default constructor on one and instantiate the other with 8. Call the increment operator on each and print their values. Then assign the second to the first and print its values.
But after I write it the output is:
The radius of the first circle is: 5
And the radius of the second circle is: 9
The radius of the first circle is: 0
And the radius of the second circle is: 0
The radius of the first circle is: 0
And the radius of the second circle is: 0
#include <iostream>
usingnamespace std;
class SimpleCircle
{
public:
SimpleCircle();
SimpleCircle( int );
SimpleCircle (const SimpleCircle & );
~SimpleCircle() {}
void SetRadius( int ) ;
int GetRadius() const ;
const SimpleCircle& operator++();
const SimpleCircle operator++( int );
SimpleCircle& operator= (const SimpleCircle &);
private:
int *itsRadius;
};
SimpleCircle::SimpleCircle()
{
itsRadius = newint(5);
}
SimpleCircle::SimpleCircle( int radius )
{
itsRadius = newint(radius);
}
SimpleCircle::SimpleCircle( const SimpleCircle & rhs)
{
int val = rhs.GetRadius();
itsRadius = newint(val);
}
SimpleCircle& SimpleCircle::operator= (const SimpleCircle & rhs )
{
if (this == &rhs)
return *this;
*itsRadius = rhs.GetRadius();
return *this;
}
const SimpleCircle& SimpleCircle::operator++()
{
++(itsRadius);
return *this;
}
const SimpleCircle SimpleCircle::operator++(int)
{
SimpleCircle temp(*this);
++(itsRadius);
return temp;
}
int SimpleCircle::GetRadius() const
{
return *itsRadius;
}
int main()
{
SimpleCircle CircleOne, CircleTwo(9);
cout << "The radius of the first circle is: " << CircleOne.GetRadius() << endl;
cout << "And the radius of the second circle is: " << CircleTwo.GetRadius() << endl;
CircleOne++;
++CircleTwo;
cout << "The radius of the first circle is: " << CircleOne.GetRadius() << endl;
cout << "And the radius of the second circle is: " << CircleTwo.GetRadius() << endl;
CircleOne = CircleTwo;
cout << "The radius of the first circle is: " << CircleOne.GetRadius() << endl;
cout << "And the radius of the second circle is: " << CircleTwo.GetRadius() << endl;
return 0;
}
What am I doing wrong? I'm using Ubuntu 10.04 Linux and g++ to run this.
you're incrementing the POINTER, not incrementing what the pointer points to. Basically you're not incrementing the radius, you're making your pointer point to something that isn't the radius.
The proper way to increment would be ++(*itsRadius)
Although, there's really no reason at all to use a pointer here. Why not just have your radius as an int? It would save you a lot of hassle, uses less memory, and is faster.