Search code examples
c++compiler-errorsconstantsmismatch

c++: no matching function call, particularly it is declared as parameter type unmatching


g++ compiler complains about:

error: no matching function for call to ‘AddressSpace::resolve(ClassOne&, ClassTwo*&, ClassThree&) const’
note: candidates are: bool AddressSpace::resolve(ClassOne&, ClassTwo*, ClassThreer) <near match>

The code causing this error is

void Class::handler(ClassOne& objOne, ClassTwo& objTwo,
        ClassThreer objThree) {

    obj.getAddressSpaceObj().resolve(objOne, objTwo.pointer, objThree);   
}

I digged into the code and found this error is caused by the reference type returned by getOtherObj() . I make it to return a const reference to the AddressSpace object in the class definition, see

const AddressSpace &getAddressSpaceObj(){
   return addressSpace;
}

After I change this definition to return a normal reference,

AddressSpace &getAddressSpaceObj(){
    return addressSpace;
}

the compiler doesn't complain about it any more. I wonder why this error is declared as parameter mismatching error? Why compiler didn't copy content as the parameters of function call but passed them as references?


Solution

  • If resolve does not have a const specifier then you can not call it on a const reference, so that would be consistent with changing it to be being non-const and having it now work. Here is a really trivial example:

    #include <iostream>
    
    class A
    {
       public:
          void someFuncA() {};
          void someFuncB() const {} ;
    } ;
    
    int main()
    {
       A
        a1 ;
       const A &aRef = a1 ;
    
       a1.someFuncA() ;
    
       // Below won't work because aRef is a const & but someFuncA() not const
       //aRef.someFuncA() ;
    
       // Below will work since someFuncB() is const
       aRef.someFuncB() ;
    }
    

    Just for completeness sake, if you uncomment aRef.someFuncA() then the error you will receive will be similar to this:

    19:19: error: no matching function for call to 'A::someFuncA() const'
    19:19: note: candidate is:
    6:12: note: void A::someFuncA() <near match>