How to preserve a LCD instance within a class?

I'm writing a class to deal with LCD. As this class will be the only part of my project that writes to LCD, I decided to include everything about LCD inside it.

I can initialize the LCD and write to it but just while in the same method. Once I try to access LCD from another method it doesn't work any more. Looks like it lost the instance.

Down bellow is my code. What can I do to fix it?

Sketch:

#include "DisplayLCD.h"

DisplayLCD myDisplayLCD("myProject");

void setup() {
  myDisplayLCD.init();
}

void loop() {
}

DisplayLCD.h

#ifndef my_display_lcd_h
#define my_display_lcd_h

#include "Arduino.h"
#include "LiquidCrystal.h"

class DisplayLCD {

  private:
    String firstMessage;
    LiquidCrystal *lcd;
        
  public:
    DisplayLCD(String firstMessage);
    void init(); 
};

#endif

DisplayLCD.cpp

#include "DisplayLCD.h"

DisplayLCD::DisplayLCD(String firstMessage) {
  this->firstMessage = firstMessage;

  pinMode(45, OUTPUT); analogWrite(45, 128); // brightness
  pinMode(44, OUTPUT); analogWrite(44, 128); // contrast
  
  LiquidCrystal liquidCrystal(33, 32, 34, 35, 36, 37);
  lcd = &liquidCrystal;
  
  lcd->begin(16, 2);
  lcd->clear();
  lcd->print(firstMessage);  
}

void DisplayLCD::init() {
// lcd->begin(16, 2);
// lcd->clear();
// lcd->print(firstMessage);    
}

I can't help, sorry, but wondering why you need to roll your own LCD library in the first place?

I don't think you posted the header file, just two copies of the cpp file.

However, in DisplayLCD you have declared an instance of LiquidCrystal and used it to initialize the display. It goes out of scope at the end of the function. It ought to be a class variable instead.

Hi wildbill,

Yes, even after a double check I missed this issue.

Here is the header file:

DisplayLCD.h

#ifndef my_display_lcd_h
#define my_display_lcd_h

#include "Arduino.h"
#include "LiquidCrystal.h"

class DisplayLCD {

 private:
   String firstMessage;
   LiquidCrystal *lcd;
       
 public:
   DisplayLCD(String firstMessage);
   void init(); 
};

#endif

Hi Vilmabergmann,

My goal, in addition to keeping the Sketch as clean as possible, is to get as much code reusable as possible.

Since only this class will handle the LCD, I have no interest in having dependencies outside it.

vilmabergmann:
I can't help, sorry, but wondering why you need to roll your own LCD library in the first place?

vilmabergmann:
I can't help, sorry, but wondering why you need to roll your own LCD library in the first place?

My goal, in addition to keeping the Sketch as clean as possible, is to get as much code reusable as possible.

Since only this class will handle the LCD, I have no interest in having dependencies outside it.