Click here to Skip to main content
15,898,222 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi i have previous experience in C#, and i am new to C++, I have a simple question. In this code when i print value of a and n they should be equal (in my opinion) but it is not the case. I wonder why it is so, variable s and *p should be pointing to same thing. If i change the order of line 5 and 6 then things got correct. My question is that why s and *p not pointing to same variable. I think i am missing some basic concept here. Please can any one explain this

C#
void EnterMentorsDataTest()
{
    Supervisor s;
    s.GetEntity();//populate s

    Project prj;
    prj.GetEntity();//populate prj


    slst.push_back(s);
    s.lstProjects.push_back(prj);


    list<Supervisor>::iterator p = slst.begin();
    while(p != slst.end())
    {
        cout<<"----------"<<endl;
        int a = s.lstProjects.size();//a will be 1
        int n = (*p).lstProjects.size();// n will be 0
        p++;
    }
}
Posted

1 solution

Value semantics.

When you do this;
C++
slst.push_back(s);

you're creating a copy of s using the copy-constructor[^] (one will be generated for you even if you don't add one. And that copy, will have no items in the list as you're never adding anything to the copy's list.

If you add a constructor to Supervisor:
C++
Supervisor(const Supervisor& other)
{
    cout << "Supervisor::Supervisor(COPY_CONSTUCTOR)" << endl;
}


you can see it being called.

Hope this helps,
Fredrik
 
Share this answer
 
Comments
leopard447 30-Mar-12 13:09pm    
Hi Fredrik,
Thanks for the reply, I am still confused a bit :( . You mean when i add an object in list the reference will not be added instead a copy of object will be created and it will be added to list? It sounds strange to me.
JackDingler 30-Mar-12 13:48pm    
That's how it works.

I assume your declaration is something like:

std::vector<Project> slst;

If you change it to:

std::vector<Project *> slst;

Then you can give it the address of the item, and that is similar to using the reference.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900