0

I'm getting a compile error when trying to use a method defined as having and option argument. The error message is this:

error: no matching function for call to 'ConsoleWidget::logInfo(const char [32])'consoleWidget->logInfo("This is logging an info message");

Below are my files.

(header) .h

#ifndef CONSOLEWIDGET_H
#define CONSOLEWIDGET_H

#include <QTextEdit>
#include <QAction>
#include <QColor>

class ConsoleWidget : public QTextEdit
{
    Q_OBJECT
public:
    explicit ConsoleWidget(QWidget *parent = nullptr);

public slots:
    void logInfo(const QString& text, const bool includeTimestamp /*=false*/);
};

#endif // CONSOLEWIDGET_H

cpp (.cpp)

void ConsoleWidget::logInfo(const QString &text, bool includeTimestamp = false)
{
    ...
}

(main) .cpp

auto *consoleWidget = new ConsoleWidget(this);
consoleWidget->logInfo("This is logging a message!");
JokerMartini
  • 5,674
  • 9
  • 83
  • 193
  • 1
    That's because `main.cpp` doesn't know about the default argument value as it's defined in the the `.cpp` file. Try defining the default argument in the header instead – xEric_xD Mar 29 '19 at 13:29
  • 3
    The default argument value must be declared in the header file. – mohabouje Mar 29 '19 at 13:31

1 Answers1

0

A default argument is (secretly) evaluated and passed by the caller of the function, so it must be known where the function is called.

If the compiler has seen

 void foo(int x = 37);

and then encounters

foo();

it will replace that with the equivalent of

foo(37);

If it has seen only void foo(int x);, there will not be a function with a matching prototype, because the function always takes an int parameter.

(This is different from, for instance, Python, where default arguments are evaluated when the function is defined and the calling code doesn't need to care.)

The solution is to move your default value from the function definition to its declaration.

molbdnilo
  • 64,751
  • 3
  • 43
  • 82