Passing a class to a class

I have a mainline sketch that is using the following library, class, and function (simplified version):

#include <TFT_eSPI.h>
:
TFT_eSPI showPanel = TFT_eSPI();
TFT_eSprite sprite = TFT_eSprite(&showPanel);
:
void somefunction() {
:
uint16_t colour = 0;
sprite.drawPixel(x, y, colour);
:
};

and I am trying to write my own class in which I would like to do the sprite.drawPixel function. In other words I would like to do the sprite.drawPixel function from within the class rather than within the main sketch.

My problem is trying to find a way to pass sprite into the class that I am writing.

I have done a bunch of searching/reading over the last couple days but am getting no where.

Ideally, I believe I would pass a pointer to sprite into my class, and then reference it somehow within class to perform the
sprite.drawPixel(x, y, colour);

However, I am totally stuck on how to define the public and private portions of the class such that I can pass the sprite in from the calling mainline sketch, as well as how to define the call in the sketch.

I hope the above is clear, and that someone can share a concreate example of how to do this correctly.

With thanks

If the sprite is also used outside of the class, this would be an option. Otherwise you could consider making sprite a member variable.

If you are using setting up an instance of sprite outside of a class then taking your example, you could possibly do something like this:

MyClass.h:

#ifndef MyClass_h
#define MyClass_h

#include <Arduino.h>
#include <TFT_eSPI.h>

class MyClass {
public:
	MyClass();
	void someFunction(TFT_eSprite &sprite);
private:
};

#endif	// MyClass.h

MyClass.cpp:

#include MyClass.h

MyClass::MyClass(){
  :
}

MyClass::someFunction(TFT_eSprite &sprite){
  :
  uint16_t colour = 0;
  sprite.drawPixel(x, y, colour);
  :
}

Main .ino:

#include <TFT_eSPI.h>
#include "MyClass"

TFT_eSPI showPanel = TFT_eSPI();
TFT_eSprite sprite = TFT_eSprite(&showPanel);

MyClass myClassInstance;

void loop {
  :
  myClassInstance.someFunction{sprite};
  :
}

This is passing by reference. The sprite object could also be passed by pointer, or as stated, included and instantiated within the class.

1 Like

Thank you - this looks super helpful. I've started to implement it and its looking pretty promising at this point. Very thoughtful of you to have posted such a thorough reply. I'm sure it will be of help to others too. Thanks again.

Edit: @bitseeker I finalized building this - the above worked great - thanks again!

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.