By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
446,190 Members | 898 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 446,190 IT Pros & Developers. It's quick & easy.

why the objects in the list giving a different address

P: 1
Expand|Select|Wrap|Line Numbers
  1. #include<iostream>
  2. #include<list>
  3. using namespace std;
  4. class a
  5. {
  6. private:
  7.     int x;
  8. public:
  9.     void setx(int xx)
  10.     {
  11.         x=xx;
  12.     }
  13.     void showx()
  14.     {
  15.         cout<<" x is "<<x;
  16.     }
  17.     void display(){
  18.         cout<<"i am in display"<<endl;
  19.         cout<<" x is "<<x <<endl;
  20.     }
  21.     void display2(){
  22.         cout<<"i am in  display2"<<endl;
  23.     }
  24.     ~a()
  25.     {
  26.         cout<<"destructor of a"<<endl;
  27.     }
  28. };
  29.  
  30. list<a> lst;
  31.     int main()
  32.     {
  33.  
  34.  
  35.         a *a1;  
  36.  
  37.         a1=new a();
  38.         a1->setx (3);
  39.  
  40.         cout<<"Address1...."<<&(*a1)<<endl;
  41.         cout<<"Address1.1..."<<a1<<endl;
  42.  
  43.         lst.push_back(*a1);
  44.  
  45.         list<a>::iterator p=lst.begin();
  46.  
  47.          cout<<"Address2......"<<&(*p)<<endl;
  48.         p->display();
  49.  
  50.         cout<<lst.size()<<endl;
  51.  
  52.         return 0;
  53.     }
  54.  
Mar 13 '07 #1
Share this Question
Share on Google+
1 Reply


sicarie
Expert Mod 2.5K+
P: 4,677
The objects in the list are giving different addresses because they are all stored at different locations - the list is what has the references to tie them together. If you used a vector, you would find that they were all contiguous in memory (if you returned many of them, there would be a pattern as the containers of the individual objects in the list are all of the same size - so there is the same amount of memory between them...). I don't believe (please anyone correct me if I'm wrong!) Lists need to have the contiguous memory space (though they can...). But each element in the list, vector, or STL container will have a different memory location because each element takes up space, and the list is ready to grow/shrink as you want it to, it just references those places the containers are at.
Mar 13 '07 #2

Post your reply

Sign in to post your reply or Sign up for a free account.