Search code examples
c++cocos2d-iphoneprotocolsvirtual

Cocos2d C++ Inheriting from a Virtual Class cuses a Linker error


I'm trying to do something similiar to an instance which hinerit from a @Protocol in Objective-C, so I would like to have a @Protocol with some declared methods, and an instance where I can override and use my methods.

With C++ for now I did a class with virtual methods liket his:

class MyClassA
{

public:
~MyClassA(){};
virtual void doSomething(argument *) = 0;

}

and a class (the one I want to instantiate and use)

class MyClassB : public MyClassA
{

public:
~MyClassB() {};
void doSomething(argument *a);

}

in the implementation file of both these classes I've implemented doSomething() like this:

void doSomething(argument *a)
{
 // yep do something
}

then in AnotherObject (which is a subclass of CCNode) I want to create an ivar of MyClassB and here's where I'm failing at, I tried to put a simple pointer to the class like:

MyClassB *myB; 

and then use it like:

myB->doSomething;

but obviously it's going to crash with bad_access

I tried to instantiate the object before using

MyClassB *myB = new MyClassB;

or

MyClassB *myB = MyClassB::create();

but got a linker error whatever I try. The error says:

Undefined symbols for architecture i386:
"MyClassB::doSomething(argument*)", referenced from:
AnotherObject::init() in AnotherObject.o
"vtable for MyClassB", referenced from:
AnotherObject::init() in AnotherObject.o

I'm missing something to achieve the same as

id<Protocol>object; 

with objective-C which I know better than C++

ps. I've decided to write Cocos2d even if this is a C++ question because of the init and create_func method that probably are in some way related


Solution

  • in the implementation file of both these classes I've implemented doSomething() like this:

    void doSomething(argument *a)
    {
     // yep do something
    }
    

    So you've defined a non-member function with the same name. You wanted to define the member function:

    void MyClassB::doSomething(argument *a)
         ^^^^^^^^^^