Search code examples
c++ooppolymorphismvirtual

Have I implemented a pure virtual function wrong?


EDIT:

I have no updated the question, whilst doing so I realized the scope of the question has completely changed, so I apologize for this. I am dealing with Threads so that static function has to be there. I have tried to abstract the Threading stuff out of the question as much as possible.

I am getting a pure virtual function call error, so I thought maybe I have the implementation wrong. Here is what I have:

class Base
{
    protected:
        virtual int f(void) = 0;
        static void baseFunction(void* param);
};

static void Base::baseFunction (void* param)
{
    Base *parent = (Base*) parameter;

    int i = parent->f();
}

class Derived : public Base
{
    private:
        int _memeber;
        int f(void);
};

int Derived::f(void)
{
    _member = 0;

    cout << "Derived _memeber is: " << _member << endl;

    return 0;
}

void main ()
{
    Derived d;

    d.baseFunction(d);
}

I need the function Derived::f(void) to have access to the Derived class members.


Solution

  • The definition looks fine, but I will hazard a guess that you're calling the virtual function from the constructor or destructor of Base. In that case, virtual dispatch is done as if the dynamic type were Base, not Derived, and if the function is pure virtual then you get undefined behaviour.

    UPDATE: You also say "I am dealing with threads". In that case, it's possible that a data race could cause one thread to call the function while another is still constructing the object - again, giving undefined behaviour. You need to make sure all data accesses are correctly synchronised.