I have a class named Renderable with one pure virtual method draw()
class Renderable : public QOpenGLFunctions
{
public:
virtual void draw() = 0;
}
And I have a class GeomObject that inherits from Renderable and also from Transformable (Transformable is a regular class, not virtual)
class GeomObject : public Renderable, public Transformable
GeomObject overloads draw() method. Also, I have a Scene class, in which I want cycle trough scene objects, and if they are Renderable, draw them. Each of them have isRenderable bool variable which is set to true. In this case, all of these objects are GeomObjects. SceneObject here is a regular class (not virtual)
for ( unsigned int i = 0; i < this->sceneObjects.count(); i++ ) {
SceneObject* obj = this->sceneObjects[i];
if ( obj->isRenderable ) {
( ( Renderable* )obj )->draw(); //access violation
}
}
This is where I get access violation. But if I cast directly to GeomObject* and then call draw(), everything works fine.
for ( unsigned int i = 0; i < this->sceneObjects.count(); i++ ) {
SceneObject* obj = this->sceneObjects[i];
if ( obj->isRenderable ) {
( ( GeomObject* )obj )->draw(); // this works
}
}
What am I doing wrong?
Here is my class hierarchy:
class Renderable : public QOpenGLFunctions
class SceneObject
class Transformable : public SceneObject
class GeomObject : public Renderable, public Transformable
Verifiable example of class hierarchy (it works, so the problem is probably somewhere else)
#include <iostream>
using namespace std;
class QOpenGLFunctions
{};
class Renderable : public QOpenGLFunctions
{
public:
virtual void draw() = 0;
};
class SceneObject
{};
class Transformable : public SceneObject
{};
class GeomObject : public Renderable, public SceneObject
{
public:
void draw(){
cout << "Draw() is called";
}
};
int main() {
GeomObject * obj = new GeomObject();
((Renderable*)obj)->draw();
return 0;
}