Skip to main content
gamedev.net
🔒 Locked

pointers to classes ... just noticed something

Started by ekrax 3 replies 450+ views
Original Post
ekrax
ekrax
this is sorta a dumb question that i think i should know the answer ... ok say we have this class sample { int x; public: set_x (int a) { x = a; } get_x () { return x; } } now say we want a pointer of this class, and we allocate some memory for it ... sample *p = new sample; obviosly to access the class members we go p -> set_x (100); then to display this we could just go cout << p -> get_x (); now say we want to allocate an array and set our pointer to that location so ... sample *p = new sample [3]; ... now here''s what i don''t get when you use this and we want to access it you go ... p[0].set_x (100) or p[1].set_x (200) ... what happend to the -> opperand ???
SiCrane
SiCrane
Using operator [] implicity dereferences the pointer, so you use . instead of ->. If you want to keep the -> then you can use pointer arithmetic instead. (p + 0)->get_x() or (p + 1)->get_x(). (Though why you would want to do so is beyond me.)
pjcast
pjcast
sample *p = new sample [3];

allocates three sample objects of which are not pointers. p is a pointer that points to the first address.

If you did new sample*[3] then you would have three pointers which you would of course have to allocate.

sample **p = new sample*[3];

p[0] = new sample;
p[1] = new sample;
p[2] = new sample;

p[0]->set_x(100)
int i = p[1]-> get_x();

**p is a pointer that points to an array of pointers (which has not been created until the call to new sample*[3]).
ekrax
ekrax
ok i understand now, thanks for your posts

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.