I am currently making a small game engine, and just faced a problem I didn't expect.
I have a root class that most classes in my engine derive from, CPObject
. CPObject
conforms to CPObjectProtocol
, an abstract class defining a few pure virtual functions.
I created another protocol, TextureProtocol
, and its concrete implementation, SDLTexture
, that also inherits from CPObject
. So far, everything works, and I can create instances of SDLTexture. However, if I make TextureProtocol
inherit from CPObjectProtocol
, clang tells me that I cannot create an instance of an abstract class.
I assumed that a class could fulfil an interface by inheriting from another class's implementation. Was I wrong?
// CPObject abstract interface/protocol
class CPObjectProtocol {
public:
virtual void retain() = 0;
virtual void release() = 0;
//more methods like this
};
// CPObject implementation.
class CPObject : public CPObjectProtocol {
public:
CPObject() { _retainCount = 0; }
virtual ~CPObject() { }
// implementation of CPObjectProtocol
virtual void retain() { _retain++; }
virtual void release() {
if(--_retainCount <= 0) {delete this;}
}
private:
int _retainCount;
};
// Texture absract interface/protocol
// inherits from CPObjectProtocol so that retain() and release()
// can be called on pointers to TextureProtocol (allowing for
// implementations to be swapped later)
class TextureProtocol : public CPObjectProtocol {
public:
virtual Color getColor() = 0;
};
// An implementation of TextureProtocol
// I assumed it would fulfil CPObjectProtocol by inheriting
// from CPObject's implementation?
class SDLTexture : public CPObject, public TextureProtocol {
public:
SDLTexture() { _id = 0; }
virtual ~SDLTexture { }
// implementation of TextureProtocol
virtual int getID() { return _id; }
private:
int _id;
}