c++pointersarduinoadafruit

Error referencing pointer object in class


Getting this error when trying to reference a pointer object.

_reader->drawBMP("/background.bmp", _tft, 0, 0);

a reference of type "Adafruit_SPITFT &" (not const-qualified) cannot be initialized with a value of type "Adafruit_ST7789 *"

I am trying to access an Adafruit library inside a class. On the above line. The code works if it's not in a class which is strange.

Main.cpp

SdFat SD;                        // SD card filesystem
Adafruit_ImageReader reader(SD); // Image-reader object, pass in SD filesys
Adafruit_ST7789 tft = Adafruit_ST7789(TFT_CS, TFT_DC, TFT_RST);
Info info(&tft, &reader, debug);

Info.h

#ifndef INFO_H
#define INFO_H

#include <Adafruit_GFX.h> // Core graphics library
#include <Adafruit_ST7789.h>
#include <SdFat.h>                // SD card & FAT filesystem library
#include <Adafruit_SPIFlash.h>    // SPI / QSPI flash library
#include <Adafruit_ImageReader.h> // Image-reading functions

class Info {
    public:
        Info(Adafruit_ST7789 *tft, Adafruit_ImageReader *reader, bool debug);
        void GenerateInfo();
    private:
        Adafruit_ST7789 *_tft;
        Adafruit_ImageReader *_reader;
        bool _debug;
};

#endif // INFO_H

Info.cpp

#include "Info.h"
#include <Arduino.h> // Include Arduino here if needed

Info::Info(Adafruit_ST7789 *tft, Adafruit_ImageReader *reader, bool debug)

{
    _tft = tft;
    _reader = reader;
    _debug = debug;
}

void Info::GenerateInfo()
{

    // Background
    _reader->drawBMP("/background.bmp", _tft, 0, 0);

}

Solution

  • The answer was in the comment and agreed to by the user.

    "Looks like you might be trying to stuff a pointer into a hole built for a reference. What happens if you dereference the pointer to get the object it points at, ie,

    _reader->drawBMP("/background.bmp", *_tft, 0, 0);
    

    so that drawBMP can take a reference to the object?"

    That is correct, but for the benefit of C++ readers, I add this background. In C++, you can have pointers and references. A pointer is variable that takes the address of an object, and a reference is a sort of an alias of an object. References are often thought of as another way of doing pointers, but I believe by the book, they don't have to be.

    Consider these functions.

    void drawBmpReference( std::string mypath, Adafruit_ST7789& something)
    void drawBmpPointer( std::string mypath, Adafruit_ST7789 *something)
    

    Then, given this:

    Adafruit_ST7789 AdaItem;
    Adafruit_ST7789 *pAdaItem;
    

    You can call either as follows:

    void drawBmpReference( "blah", AdaItem );
    void drawBmpPointer( "blah", &AdaItem );
    void drawBmpReference( "blah", *pAdaItem );
    void drawBmpPointer( "blah", pAdaItem );
    

    Hope that helps