Results 1 to 2 of 2

Thread: Question about pointer to class

  1. #1
    Join Date
    Jan 2007
    Posts
    12
    Thanks
    2
    Qt products
    Qt4
    Platforms
    Windows

    Default Question about pointer to class

    Hi I have a question on pointer to class, please have a look at the snippet below:

    Code to instantiate the class through use of pointer

    Qt Code:
    1. #include <iostream>
    2. using namespace std;
    3.  
    4. class Rect
    5. {
    6. public:
    7. int x;
    8. Rect();
    9. };
    10. Rect::Rect()
    11. {
    12. x = 5;
    13. }
    14.  
    15. int main()
    16. {
    17. Rect *re = new Rect;
    18. std::cout << re << std::endl;
    19. std::cout << &re << std::endl;
    20. std::cout << re->x << std::endl;
    21. system("PAUSE");
    22. return 0;
    23. }
    24. */
    To copy to clipboard, switch view to plain text mode 

    Below is the result from the console:
    [HTML]
    0x33ffc0
    0x23ff70
    5[/HTML]

    My question, when I try to output re to the console, I assume it will take the address of the object instantiated, and it wrote 0x33ffc0, but when I called for &re, it wrote 0x23ff70. Doesn't &re means I'm displaying the address of the variable pointing to?

    So why are they different?
    I thought that re contains the address of the object instantiated, and &re should get the address of the object too, as defined in most tutorials on pointer.


    doing std::cout << *re will give me an error. I understand from the concept of pointers, that *var will get the value pointed by the pointer. Is my assumption correct that the value is of an object and can't be displayed?

    Thanks for reading this, I'm very curious at this, but it's indeed interesting to me!

  2. #2
    Join Date
    Jan 2006
    Location
    Gloucester, UK
    Posts
    18
    Thanked 1 Time in 1 Post
    Qt products
    Qt3 Qt4
    Platforms
    Unix/X11 Windows

    Default Re: Question about pointer to class

    No.
    re and &re are not the same.
    re is a pointer to the variable of class rect. so re is a *Rect

    &re is the address of where the pointer re is stored.
    So &re is **Rect

Similar Threads

  1. simple pointer question
    By mickey in forum General Programming
    Replies: 6
    Last Post: 16th June 2006, 09:19
  2. Replies: 2
    Last Post: 4th May 2006, 19:17
  3. Beginner C++ question
    By masoroso in forum General Programming
    Replies: 2
    Last Post: 19th April 2006, 14:15
  4. Qt in other class
    By Morea in forum Qt Programming
    Replies: 4
    Last Post: 9th April 2006, 17:08
  5. Replies: 5
    Last Post: 15th March 2006, 07:33

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
Digia, Qt and their respective logos are trademarks of Digia Plc in Finland and/or other countries worldwide.