I am learning c++ from 'Teach yourself c++ in 21 days' by Liberty and Jones. Compiler I am using is gcc 6.3.0. I am on pointer topic. First I am writing one code similar to the one book gives which works fine. Here it is:
#include <iostream>
using namespace std;
class Cat
{
public:
Cat();
int Getage() {return *itsage;}
private:
int *itsage;
};
Cat::Cat()
{
itsage=new int;
*itsage=2;
}
int main()
{
Cat *Mani=new Cat;
cout << "Mani is a cat whose age is: " << Mani->Getage();
cout << endl;
return 0;
}
Output: Mani is a cat whose age is: 2
Now instead of using constructor, I thought of using accessor function to set age. I wrote the following code which gave me output as above but I have doubt why this code work. Here is the code I wrote.
#include <iostream>
using namespace std;
class Cat
{
public:
void Setage(int age) {*itsage=age;}
int Getage() {return *itsage;}
private:
int *itsage;
};
int main()
{
Cat *Mani=new Cat;
Mani->Setage(2);
cout << "Mani is a cat whose age is: " << Mani->Getage();
cout << endl;
return 0;
}
Doubt: What I studied so far tells me that whenever pointer declared, it should get initialized, i.e. we should assign some memory address to it. In the first code, we are initializing our pointer member variable in the constructor by this command itsage=new int;
which looks fine. But in the second code, I nowhere assigned any memory address to pointer itsage. But still code worked fine. I am little confused here.
I have one more doubt(I am asking here itself as it is related to the above code. If it's bad, I will ask it in different question.) I thought of making pointer itsage in the above code public. But I don't know how can I access it. I tried the following but didn't work.
#include <iostream>
using namespace std;
class Cat
{
public:
int *itsage;
};
int main()
{
Cat *Mani=new Cat;
Mani->*itsage=2;
cout << "Frisky's age is " << Mani->*itsage;
return 0;
}
So how to access public pointer member variable of object created on heap?
Thanks.