Search code examples
c++inheritancevirtual

Problem implementing virtual method in derived class


Hey I was trying to multiple inherit a pure virtual function using MVS2010 Compiler. So I can run a draw for all renderable objects.

So here is the diagram

in ASCII

|Renderable            | |Entity             |
|virtual bool draw()=0;| | functions in here |

    is - a              is - a


                Shape

So it seems it wont let me inherit the pure virtual function? and implement the virtual function. Here is my code.

// Renderable.h
#ifndef H_RENDERABLE_
#define H_RENDERABLE_
class Renderable
{
 public:
    virtual bool Draw() = 0;
};
#endif


 //Shapes.h
 #ifndef H_SHAPES_
 #define H_SHAPES_
 #include "Renderable.h"
 #include "Entity.h"
 class Shapes : public Entity, public Renderable
 {
 public:
     Shapes();
     ~Shapes();

 };


 #endif

 //shapes.cpp
 #include "Shapes.h"


 Shapes::Shapes()
 {
 }


 Shapes::~Shapes()
 {
 }


 virtual void Shapes::Draw()
 {
 }

I have tried multiple things and it doesn't work also google searched.


Solution

  • First, you need to declare the draw function again in your Shapes class. Then make sure it has the same signature as the one declared in the Renderable class.

    //Shapes.h
     #ifndef H_SHAPES_
     #define H_SHAPES_
     #include "Renderable.h"
     #include "Entity.h"
     class Shapes : public Entity, public Renderable
     {
     public:
         Shapes();
         ~Shapes();
    
         virtual bool Draw();
    
     };
    
    
     #endif
    
     //shapes.cpp
    
    bool Shapes::Draw()
    {
    }