General question about virtual functions and inheretence

I’ve spent the entire day trying to get some simple C++ inheritance to work properly and could definitely use some assistance. I realize that this may not be openFrameworks related, but it’s definitely for an openFrameworks project! :slight_smile:

I have a class called Observer that looks like this:

  
  
class Observer  
{  
  
public:  
  
    virtual void notify(int message_type) const { printf("Observer::notify called."); }  
    virtual ~Observer() {};  
};  
  

I have a class which represents a generic “Module” which inherits from Observer:

  
  
class Module : public ofBaseApp, public Observer {  
  
private:  
  
  // stuff  
  
public:  
  
    Module() { };  
    ~Module() { };  
    void setup(int pos_x, int pos_y, int width, int height);  
    void draw();  
    void dataupdated();  
  
    virtual void notify(int message_type) const { printf("Module::notify called."); };  
};  
  

Finally, I have a specific module called “ExampleModule”, which inherits from Module and looks like this:

  
  
class ExampleModule : public Module {  
  
    ~ExampleModule() { };  
  
public:  
  
    void notify(int message_type) const { printf("ExampleModule::notify called."); };  
};  
  

This works OK. If I instantiate an ExampleModule and call notify(), the output is “ExampleModule::notify called.”. However, if I change ExampleModule’s class definition so that the notify() function is not defined inline, calling notify will output: “Module::notify called.”

I’ve attempted a lot of variations in how and where to define notify(). I tried making it a pure virtual function in class Observer, but that ended up throwing a “Undefined reference to vtable … something … something” error. Would it be helpful if I posted the code that causes the “undefined reference to vtable” error?

Thanks!

  • Bret

Nevermind! I figured it out! My working code looks like this:

  
  
  
class Observer {  
  
public:  
  
    virtual void notify(int message_type) = 0;  
  
};  
  
  
class Module : public ofBaseApp, public Observer {  
  
public:  
  
    virtual void notify(int message_type) = 0;  
  
};  
  
  
class ExampleModule : public Module {  
  
public:  
  
    void notify(int message_type); // this is defined in the C++ file, not inline  
};  
  
  

hi clone45,

yes, that will work - however it should have worked the first time also! out of interest - did you ever try cleaning the project and then rebuilding? sometimes with inline functions the compiler can get confused and miss a change somewhere…