Question

I have the following class:

class gkLogicBrick
{
public:
    gkLogicBrick(gkGameObject* object, gkLogicLink* link, const gkString& name);
    virtual ~gkLogicBrick();

    virtual gkLogicBrick* clone(gkLogicLink* link, gkGameObject* dest) = 0;

    //unimportant function/variables
};

and it's being subclassed like:

class gkLogicController : public gkLogicBrick
{
    gkLogicController(gkGameObject* object, gkLogicLink* link, const gkString& name);
    virtual ~gkLogicController() {}

    //unimportant function/variables
};

The method named clone() isn't being overridden and yet it is being called from another class on a gkLogicController object. I thought calling pure virtual functions wasn't allowed? Do C++ compilers automatically create a default definition for any pure virtual functions inherited?

Was it helpful?

Solution

It's OK to call a pure virtual function (through the dynamic dispatch mechanism). That is actually the purpose of pure virtual functions, when you think about it.

I assume that "being called from another class on a gkLogicController object" actually means through a pointer or reference to gkLogicController. This must then point/refer to an instance of a class derived from gkLogicController which does override clone. It is impossible to create an instance of gkLogicController itself, as it is still abstract.

OTHER TIPS

I guess you have not compiled your code. Because

struct A
{
    virtual void test()=0;
};

struct B : A
{

};

int main()
{
    B b;    
}

http://ideone.com/Dbx9iH

see the error:

prog.cpp: In function ‘int main()’: prog.cpp:13:7: error: cannot declare variable ‘b’ to be of abstract type ‘B’ prog.cpp:6:8: note: because the following virtual functions are pure within ‘B’: prog.cpp:3:18: note: virtual void A::test()

If you do not define the function SOMEWHERE in an actual class (e.g. a derived class), you will get an error when trying to create the object (at compile time).

It is however fine to not have one in the baseclass if the baseclass is never directly instantiated - in fact, it's often used this way just TO make sure the baseclass isn't accidentally "used" when it shouldn't be. If the baseclass is intended to be used, then you do need to implement the function (you can still do that even if it says = 0 on the end.

And the whole point of virtual functions is to allow the baseclass (or some other component that only knows about the baseclass) to call the actual function in the derived class.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top