Forum Rule: Always post complete source code & details to reproduce any issue!
Results 1 to 3 of 3

Thread: Virtual functions on Teensy3

  1. #1

    Virtual functions on Teensy3

    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.

  2. #2
    Join Date
    Dec 2012
    Adelaide, SA
    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

  3. #3
    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.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts