shengyushen
shengyushen

Reputation: 289

missing "const" leading to "error: no matching function for call to"

I have a class ssyvector like this:

class ssyvector {
public :
  ssyvector( ssyvector& a);

It have a constructor that accept a reference to another ssyvector.

I further define an operator+ like this

ssyvector operator+(const ssyvector& a,const ssyvector& b)

I try to apply this operator to two ssyvectors like this:

ssyvector c10000 = s10000+a10000;

Then g++ complain that :

main.cpp:31:28: error: no matching function for call to ‘Ssyvector::ssyvector::ssyvector(Ssyvector::ssyvector)’
  ssyvector c10000 = s10000+a10000;
                            ^

I can remove this error by add "const" keyword to definition of constructor like this:

class ssyvector {
public :
  ssyvector( const ssyvector& a);

It seems so confusing, can someone explain this? Thanks

Upvotes: 0

Views: 598

Answers (1)

Buddy
Buddy

Reputation: 11028

The operator+ is returning a temporary object. You can only take const references to temporary objects.

Also your constructor should take a const reference, since making a copy of something shouldn't change the thing being copied (unless we get into quantum mechanics...)

Upvotes: 1

Related Questions