views:

54

answers:

1

Hi,

I am working in migration project from VC6 to VC9. In VC9 (Visual Studio 2008), I got compilation error while passing const member to a method which is accepting reference. It is getting compiled without error in VC6.

Sample Program:

class A
{
};

typedef CList<A, A&> CAlist;

class B
{
    CAlist m_Alist;

public:
    const B& operator=( const B& Src);
};

const B& B::operator=( const B& Src)
{
    POSITION pos = Src.m_Alist.GetHeadPosition();

    while( pos != NULL)
    {
        **m_Alist.AddTail( Src.m_Alist.GetNext(pos) );**
    }

    return *this;
}

Error: Whiling compiling above program, I got error as

error C2664: 'POSITION CList::AddTail(ARG_TYPE)' : cannot convert parameter 1 from 'const A' to 'A &'

Please help me to resolve this error.

+1  A: 

That is because the GetNext() method returns a temoprary object of class A and the function AddTail takes the parameter A&. Since a temporary object can not be bound to a non-const reference you get the error. The simplest way to solve it is to break it into two statements. For example:

    while( pos != NULL)
    {
        A a =  Src.m_Alist.GetNext(pos);
        m_Alist.AddTail(a);
    }
Naveen
It is working fine in sample program. But it is not working in the migration project since it is giving error as "no copy constructor available or copy constructor is declared 'explicit'". I resolved that issue using like belowSample code:-A a;a = Src.m_Alist.GetNext(pos); m_Alist.AddTail(a);Now its working fine in my project also. Thanks.
Snabak Vinod