0

I just created a cool class in a namespace and therefore I wanted to create 2 functions. They should have the same name, but different parameters.

But every time I compile it, it says:

.....formatter.cpp:25:18: error: no matching member function for call to 'output'
return this->output(DateTime());
       ~~~~~~^~~~~~
.....formatter.h:57:18: note: candidate function not viable: expects an l-value for 1st argument
    const string output(DateTime& time) const;
                 ^
.....formatter.cpp:23:25: note: candidate function not viable: requires 0 arguments, but 1 was provided
const string Formatter::output() const
                        ^

So I assumed that I had done a typo or something, but without success. Because of that I ended up here. Here is the minimized class:

formatter.h

namespace test {
    class Formatter
    {
    public:
        const string output() const;
        const string output(DateTime& time) const; //DateTime is another class in the same namespace
    }
}

formatter.cpp

namespace test {
    const string Formatter::output() const
    {
        return output(DateTime());
    }

    const string Formatter::output(class DateTime& time) const
    {
        return "Test";
    }
}

Thanks for your help, ~ Markus

And I swear, I have tried any possibility without success...

petritz
  • 182
  • 1
  • 9

2 Answers2

2

C++ doesn't allow binding of temporaries (rvalues) to non-const lvalue references, which is what you're doing here:

return output(DateTime());

You can fix this by making the parameter a const reference:

const string output(const DateTime& time) const;
juanchopanza
  • 223,364
  • 34
  • 402
  • 480
0

You need

const string output(const DateTime& time) const;

Your calling pattern (DateTime()) creates a temporary. A non-const reference cannot bind to a temporary. You need a const reference.

user93353
  • 13,733
  • 8
  • 60
  • 122