I've got a couple of questions, I'm just a little curious as to what is going on, I am doing a workshop for teach yourself c++ in 21 days. My code works but it differs from the answers.
First of all I am to write a class, its functions and a single variable easy enough, I am also
to implement 2 constructors a copy constructor and prefix and postfix operators. Then I am to
change the 1 variable to be on the free store, and fix everything accordingly.
The questions I have are regarding the initialization stage of the constructors and the prefix/
postfix operator functions.
In my contructors before using the free store I have...
Code:
SimpleCircle::SimpleCircle():
itsRadius(5)
{}
SimpleCircle::SimpleCircle(USHORT r):
itsRadius(r)
{}
Default initializes to 5. The answers are the same, but...
after the free store I have...
Code:
SimpleCircle::SimpleCircle():
itsRadius(new USHORT(5))
{}
SimpleCircle::SimpleCircle(USHORT r):
itsRadius(new USHORT(r))
{}
The answer is...
Code:
SimpleCircle::SimpleCircle()
{
itsRadius = new USHORT(5);
}
SimpleCircle::SimpleCircle(USHORT r)
{
itsRadius = new USHORT(r);
}
Is there any difference between the 2 methods? Preferred or otherwise? Like I said my code works.
Onto the prefix/postfix.
Before the free store change I had...
Code:
const SimpleCircle& SimpleCircle::operator++()
{
++itsRadius;
return *this;
}
const SimpleCircle SimpleCircle::operator++(int)
{
SimpleCircle temp;
++itsRadius;
return temp;
}
The answer is...
Code:
const SimpleCircle& SimpleCircle::operator++()
{
++(itsRadius);
return *this;
}
const SimpleCircle SimpleCircle::operator++(int)
{
SimpleCircle temp(*this);
++(itsRadius);
return temp;
}
Whats with the parenthesis? and do you have to put (*this) ?
Ok after the free store change I have...
Code:
const SimpleCircle& SimpleCircle::operator++()
{
++(*itsRadius);
return *this;
}
const SimpleCircle SimpleCircle::operator++(int)
{
SimpleCircle temp;
++(*itsRadius);
return temp;
}
The * to dereference itsRadius but in the answer...
Code:
const SimpleCircle& SimpleCircle::operator++()
{
++(itsRadius);
return *this;
}
const SimpleCircle SimpleCircle::operator++(int)
{
SimpleCircle temp(*this);
++(itsRadius);
return temp;
}
The (*this) is there still, but itsRadius is not dereferenced! I tried it like this and got
strange output so is there a mistake in the answers or could I have missed something else
entirely?
Thanks