pointers - Address of a member data stored on heap memory -
i'm learning c++ , i've got question, material i'm using. think there may errors in editing, i'm quite not sure. book's name "c++ through game programming".
here's code in book, it's in chapter 9.
class critter { public: critter(const string &name = "", int age = 0); ~critter(); critter(const critter &c); critter& operator=(const critter& c); void greet() const; private: string *mname; int mage; }; critter::critter(const string &name, int age) { cout << "constructor called\n"; mname = new string(name); mage = age; } critter::~critter() { cout << "destructor called\n"; delete mname; } critter::critter(const critter &c) { cout << "copy constructor called\n"; mname = new string(*(c.mname)); mage = c.mage; } critter& critter::operator=(const critter& c) { cout << "overloading assignment operator called\n"; if (this != &c) { delete mname; mname = new string(*(c.mname)); mage = c.mage; } homecoming *this; } void critter::greet() const { cout << "i'm " << *mname << " , i'm " << mage << " years old.\n"; cout << "&mname: " << &mname << endl; }
here i'm creating critter class, , test allocate heap memory. can see, declared pointer *mname point string object on heap memory.
so confusing me that, in lastly method: void critter::greet() const "the address of string on heap stored in pointer m_pname" &mname, print out in method.
but think mname address of string object stored on heap. &mname address of pointer itself.
to create clear, seek print &mage also.
and got is:
&mname: 0x7fff5fbff640 mname: 0x100103b20 &mage: 0x7fff5fbff648
as can see, &mname , &mage have similar address, mname's different. maybe mname points heap, , &mname , &mage addresses belong stack.
that's think, tried find errata of book found nothing. can guys create clear me. right or might have misunderstanding.
thanks help. appreciate it.
you have right. because mname
pointer, value of pointer address of string object points to. &mname
address pointer stored.
pointers heap-memory stack-memory
No comments:
Post a Comment