or it's a simple mistake. Instead of
cout << "Cat's Age is: " << c->getAge;
it should be
cout << "Cat's Age is: " << c->getAge();
-haro
Mike Wahler wrote:
"Yin99" <ws@ziowave.com> wrote in message
news:1123185796.546485.279760@z14g2000cwz.googlegroups.com...
I'm expecting to see itsAge = 0 in the output of the following code.
However, in the main() function, itsAge = 1 . Can someone explain??
thanks,
Yin99
===== begin code ======
#include <iostream>
using namespace std;
class Cat
{
public:
Cat(){
itsAge = 0;
cout << "constuctor age is: " << itsAge; //zero here!
}
This is not part of your reported problem, but a constructor
should use an initializer list instead of assigning values to
members after the fact:
Cat() : itsAge(0) {
cout << "constuctor age is: " << itsAge << '\n';
}
void setAge(int age){
itsAge = age;
}
int getAge(){
return itsAge;
}
Again, not part of your problem, but more correct is:
int getAge() const {
return itsAge;
}
private:
int itsAge;
};
int main ()
{
Cat *c = new Cat();
Yet again, not part of your problem, but why are you dynamically
allocating your object? Why not just define it, e.g.:
Cat my_cat;
//c->getAge returns 1 here, Why and Where does 1 come from?
cout << "Cat's Age is: " << c->getAge;
Try:
cout << "Cat's Age is: " << c->getAge();
return 0;
}
I suspect the output of 1 is because you were passing the address
of a function, for which theres no << overload, so it's probably
being converted to a bool, to which assigning any nonzero value
will result in a value of one.
-Mike
.