Having a virtual method with polymorphism seems to cause a linker problem [duplicate]

  arduino, arduino-esp8266, c++, esp8266, polymorphism

I have the following C++ classes:

This first class is an abstract class and should not be instantiated directly:

class Logger
{
public:
    enum LogLevel
    {
        Error,
        Info,
        Debug
    };

    virtual void log(const char *str, const LogLevel log_level) const;
    virtual ~Logger() = default;

protected:
    Logger() = default;
};

Then we have one child class that derives from the base abstract Logger:

class SerialLogger : public Logger
{
public:
    SerialLogger(unsigned long baud_rate);
    ~SerialLogger();

    void log(const __FlashStringHelper *in_flash_str, const LogLevel log_level) const;
    void log_debug(const __FlashStringHelper *in_flash_str) const;
    void log_info(const __FlashStringHelper *in_flash_str) const;
    void log_error(const __FlashStringHelper *in_flash_str) const;

    void log(const char *str, const LogLevel log_level) const override
    {
        // SOME LOGIC HERE ...
    }
};

In my main, this SerialLogger is instantiated and passed as an argument to a some_object (ignoring the slicing issue now), and it is saved as a Logger type.

Logger logger = SerialLogger(15200);
SomeOtherClass some_object(logger);

However, when building the project, I get the following linker error, and I am not sure why:

Linking .piobuildesp01_1mfirmware.elf
c:/users/MYUSER/.platformio/packages/toolchain-xtensa/bin/../lib/gcc/xtensa-lx106-elf/10.2.0/../../../../xtensa-lx106-elf/bin/ld.exe: .piobuildesp01_1msrcconfiguration_manager.cpp.o:(.text._ZN20ConfigurationManagerC2ER6Logger+0x0): undefined reference to `_ZTV6Logger'
collect2.exe: error: ld returned 1 exit status
*** [.piobuildesp01_1mfirmware.elf] Error 1

It seems to have something to do with the virtual log method in the Logger base class, because removing virtual from the base and the overriding from the derived removes the problem.

Could anyone tell me what is going on and how to solve that?

Source: Windows Questions C++

LEAVE A COMMENT