A question regarding stl set
CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3

Thread: A question regarding stl set

Hybrid View

  1. #1
    Join Date
    Jul 2005
    Posts
    894

    A question regarding stl set

    Here is the code,
    Code:
    #include <set>
    
    using namespace std;
    
    class A
    {
    public:
    	void bar()
    	{
    		cout<<"bar"<<endl;
    	}
    };
    
    void foo(A& a)
    {
    	a.bar();
    }
    
    int main()
    {
    	set<A> setA;
    
    	A a;
    	for(set<A>::iterator it=setA.begin();it!=setA.end();++it)
    	{
    		a = *it;
    
    		foo(*it);
    	}
    
    	return 0;
    }
    If I call foo(*it), then I get an error " error C2664: 'foo' : cannot convert parameter 1 from 'const A' to 'A &' ". But if I call foo(a), then it would compile just fine. Why? What is the difference between a and *it. I thought they are basically the same. Thanks.

  2. #2
    Join Date
    Aug 2000
    Location
    West Virginia
    Posts
    7,564

    Re: A question regarding stl set

    Because foo() could (potentially) modify the parameter that is passed.

    So ... foo(*it) , could modify an element in the set (which is not allowed,
    since it could mess up the ordering).

  3. #3
    Join Date
    Apr 2000
    Location
    Belgium (Europe)
    Posts
    3,765

    Re: A question regarding stl set

    there is a difference...
    a = *it; with foo(a)
    assigns/copies *it into an existing object a. then you call foo on an object that is not const. which is ok.

    in the foo(*it) case, you're trying to pass "const" *it to a function that epxects a modifiable object reference.

    if you changed foo to foo(const A& a) then you could call foo(*it).
    in this particular case, since foo() calls A::bar(), you would also have to change bar to void bar() const;

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  


Azure Activities Information Page

Windows Mobile Development Center


Click Here to Expand Forum to Full Width

This is a CodeGuru survey question.


Featured


HTML5 Development Center