unexpected return value

Y

Yin99

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!
}

void setAge(int age){
itsAge = age;
}

int getAge(){
return itsAge;
}


private:
int itsAge;
};


int main ()
{

Cat *c = new Cat();
//c->getAge returns 1 here, Why and Where does 1 come from?
cout << "Cat's Age is: " << c->getAge;
return 0;

}
 
M

Mike Wahler

Yin99 said:
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:

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,014
Latest member
BiancaFix3

Latest Threads

Top