Initializing an object within an object

I’m writing a class which takes the LiquidCrystal_I2C.h library and adds my own custom functions. As a demo, I wrote the following sketch that threw an error on compile saying mylcd was not declared in scope.

#include <LiquidCrystal_I2C.h>

class testLCD{
public:
  testLCD(){
      LiquidCrystal_I2C mylcd(39, 20, 4);
  }

  void print(String stuff){
      mylcd.print(stuff);
  }

};

void setup() {

}

void loop() {

}

I read here that the LiquidCrystal_I2C object should be declared in the class body first before being initialized in the constructor (correct me if I interpreted the advice wrongly), which I corrected in the following:

#include <LiquidCrystal_I2C.h>

class testLCD{
public:
  LiquidCrystal_I2C mylcd;
  testLCD(){
      LiquidCrystal_I2C mylcd(39, 20, 4);
  }

  void print(String stuff){
      mylcd.print(stuff);
  }

};

void setup() {

}

void loop() {

}

…which now throws “no matching function for call to LiquidCrystal_I2C::LiquidCrystal_I2C()’”. The LiquidCrystal_I2C library is available off library manager if you need to download it.

Advice would be appreciated.

You need to use an Initializer List. See Case #3.

Short and sweet answer, thanks!