Jump to content
  • Advertisement

Archived

This topic is now archived and is closed to further replies.

ekrax

pointers to classes ... just noticed something

This topic is 5277 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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 ???

Share this post


Link to post
Share on other sites
Advertisement
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.)

Share this post


Link to post
Share on other sites
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]).

Share this post


Link to post
Share on other sites
Guest Anonymous Poster

sample *p = new sample;
p[0].set_x(100);

works too.

Share this post


Link to post
Share on other sites

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!