0

The code below fails to instantiate the Display_OpenGL class, because it does not consider the Surface implementation from Surface_OpenGL to map with the Display : Surface class.

Uncommenting this line fix the problem but then this is not elegant. //void Draw() { Surface_OpenGL::Draw(); }

Is there's a better solution for what I want to do? Draw is already defined in Surface_OpenGL, but it seems like it needs to be defined explicitly for Display as well, any nice solutions?

Thank you.

class Surface
{
    public:
    virtual void Draw() = 0;
};

class Display : public Surface
{
};

class Surface_OpenGL : public Surface
{
    public:
    void Draw(){}
};

class Display_OpenGL : public Display, public Surface_OpenGL
{
    public:
    //void Draw() { Surface_OpenGL::Draw(); }
};

#define WIN32_LEAN_AND_MEAN
#include <windows.h>
int WINAPI WinMain(HINSTANCE, HINSTANCE, LPSTR, int)
{
    //Error cannot instantiate abstract class
    Display *display = new Display_OpenGL();

    display->Draw();
    delete display;
    return 0;
}
Valrandir
  • 23
  • 2

1 Answers1

2

This is like he classic diamond inheritance case. Try:

class Surface
{
    public:
    virtual void Draw() = 0;
};

class Display : virtual public Surface
{
};

class Surface_OpenGL : virtual public Surface
{
    public:
    void Draw(){}
};

class Display_OpenGL : public Display, public Surface_OpenGL
{
    public:
    //void Draw() { Surface_OpenGL::Draw(); }
};

#define WIN32_LEAN_AND_MEAN
#include <windows.h>
int WINAPI WinMain(HINSTANCE, HINSTANCE, LPSTR, int)
{
    //Error cannot instantiate abstract class
    Display *display = new Display_OpenGL();

    display->Draw();
    delete display;
    return 0;
}
George Houpis
  • 1,729
  • 1
  • 9
  • 5
  • Most Excellent™ Just when I though I had a very good grasp on C++, I learn something new. Thank you very much sir. – Valrandir Jan 28 '15 at 18:53