Snabak Vinod
Snabak Vinod

Reputation: 120

How to resolve compilation error "cannot convert const to reference" in VC++9

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.

Upvotes: 2

Views: 1942

Answers (1)

Naveen
Naveen

Reputation: 73443

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);
    }

Upvotes: 1

Related Questions