Virtual functions on Teensy3

Not open for further replies.

Roger Parkinson

Active member
Has anyone tried overiding inherited virtual functions on the Teensy3?
This is my code:
class App {
	virtual ~App() {};
	virtual void init() { Serial.println("App::init()"); };
	App() {};

class GraphicTest : public App {
	GraphicTest() :App() {};
	virtual void init() { Serial.println("GraphicTest::init()"); };
	virtual ~GraphicTest() {};
App app = GraphicTest();
The output I hope to see is "GraphicTest::init()", instead I see "App::init()", which is what I'd expect if they were not virtual functions.
Sorry if this is a dumb question. I used to know this stuff but I've been away from C++ for about a decade. I did look at some tutorials though.
Thanks for any help.
This wouldn't be Teensy specific... You're assigning a GraphicTest object to an App object. It is likely using some default (ie shallow copy) assignment operator or copy constructor, and what you wind up with *is* an App, not a GraphicTest. The GraphicTest object is created as a temporary, used to initialise-copy to the App, then deleted.

Perhaps you want to use a pointer (or a reference), and do something like:

App *app = new GraphicTest();

This way you wind up keeping a real GraphicTest object.

- Peter
That worked, thanks. I had been staring at the class defs and not looking at the way I was invoking them.
I need to re-learn all that pointer stuff in C++. Java has spoiled me.
Not open for further replies.