Home > other >  How to pass a reference to an object to another class
How to pass a reference to an object to another class

Time:01-27

I'm trying to pass a reference to an object from my main.cpp to menux.cpp however I'm getting this error:

error: conflicting declaration 'MenuX alpha4' MenuX(alpha4);

main.cpp

#include "MenuX.h"
Adafruit_AlphaNum4 alpha4 = Adafruit_AlphaNum4();
MenuX(alpha4);

MenuX.h

#ifndef MENUX_H
#define MENUX_H

#include "Adafruit_LEDBackpack.h"
#include <Adafruit_GFX.h> // Core graphics library

class MenuX
{
public:
    MenuX(Adafruit_AlphaNum4 *alpha4);
    void addX();

private:
    Adafruit_AlphaNum4 *xLed;
};

#endif

MenuX.cpp

#include "MenuX.h"

MenuX::MenuX(Adafruit_AlphaNum4 *alpha4) {
    xLed = alpha4;
}
void MenuX::addX()
{
    xLed->writeDigitAscii(0, 'X');
    xLed->writeDigitAscii(1, 'X');
    xLed->writeDigitAscii(2, 'X');
    xLed->writeDigitAscii(3, 'X');
    xLed->writeDisplay();
}

CodePudding user response:

  • You don't have your main code inside of a main function
  • You can create the alpha4 in main without creating and assigning a temporary
  • The MenuX constructor takes a pointer so you need to pass &alpha4
  • Not an error but probably a mistake, you don't use the MenuX you've created
#include "MenuX.h"

int main() {
    Adafruit_AlphaNum4 alpha4;
    MenuX menu(&alpha4);  // added & and object name
}
  •  Tags:  
  • c
  • Related