Maria Ines Parnisari
Maria Ines Parnisari

Reputation: 17506

C++ compiler error "no matching function"

These are the two functions involved:

int FixedLengthRecordFile :: write (const int numRec, const FixedLengthFieldsRecord & rec)
{
    /*** some code ***/

    return rec.write(file); // FILE* file is an attribute of FixedLengthRecordFile
}


int FixedLengthFieldsRecord :: write (FILE* file) { /* ... code ... */ }

And I get this error:

FixedLengthRecordFile.cpp: In member function ‘int FixedLengthRecordFile::write(int, const FixedLengthFieldsRecord&)’:
FixedLengthRecordFile.cpp:211:23: error: no matching function for call to ‘FixedLengthFieldsRecord::write(FILE*&) const’
FixedLengthRecordFile.cpp:211:23: note: candidate is:
FixedLengthFieldsRecord.h:35:7: note: int FixedLengthFieldsRecord::write(FILE*) <near match>
FixedLengthFieldsRecord.h:35:7: note:   no known conversion for implicit ‘this’ parameter from ‘const FixedLengthFieldsRecord*’ to ‘FixedLengthFieldsRecord*’
FixedLengthRecordFile.cpp:213:1: warning: control reaches end of non-void function [-Wreturn-type]

What is the cause of the error? I don't see anything wrong in the code. Besides, I've got two other similar functions (write), and it works just fine.

Upvotes: 1

Views: 1318

Answers (2)

Arun
Arun

Reputation: 20393

Lets look at the error message:

FixedLengthFieldsRecord.h:35:7:note: int FixedLengthFieldsRecord::write(FILE*)<near match>
FixedLengthFieldsRecord.h:35:7:note:   no known conversion for implicit ‘this’ parameter
    from ‘const FixedLengthFieldsRecord*’ to ‘FixedLengthFieldsRecord*’

It says that it cannot do a conversion from const FixedLengthFieldsRecord* to FixedLengthFieldsRecord*

That is a pretty good hint.

In the following line, rec is const reference,

return rec.write(file); // FILE* file is an attribute of FixedLengthRecordFile

But the following function is NOT const qualified

int FixedLengthFieldsRecord :: write (FILE* file) { /* ... code ... */ }

Hence the problem!

There are (at least) two solutions:

1) Change rec to a non-const reference

2) Change the signature of the write() method to be const qualified

Option #2 is the preferred approach.

Upvotes: 0

taocp
taocp

Reputation: 23664

int FixedLengthRecordFile::write( const int numRec, 
                                  const FixedLengthFieldsRecord& rec)
{
   /*** some code ***/

    return rec.write(file); // FILE* file is an attribute of FixedLengthRecordFile
}


int FixedLengthFieldsRecord::write(FILE* file) 

You pass parameters by const and const reference, however, the function rec.write(file) you called is not a const function, which may modify those passed in objects, therefore, compiler complains.

You should do the following:

   int FixedLengthFieldsRecord::write(FILE* file)  const  
       // add const both declaration and definition ^^^

Upvotes: 3

Related Questions