Question

Developing on Ubuntu using Eclipse/gcc with -std=c++0x.

I seem to be having an issue with object slicing, that doesn't fall under the other questions I've seen here. I have a very simple base class / child class inheritance model. Base class has one pure virtual function which obviously the child implements:

class Parent{
public:
    Parent();
    virtual ~Parent();
    virtual void DoStuff() = 0;
};

class Child : public Parent{
public:
    Child();
    virtual ~Child();
    virtual void DoStuff(); //Child can have "grandchildren"
};

What I want is to have a queue where I can store these objects for processing by a worker thread. I know I should be storing pointers, or else I'd guarantee slicing. So, in the class ("Processor") which does this I have:

typedef queue<Parent*> MYQUEUE; //#include <queue>
static MYQUEUE myQueue;

//Call this after creating "Child c;" and passing in &c:
void Processor::Enqueue(Parent* p) 
{
    myQueue.push(p);
}

void* Process(void* args) //function that becomes the worker thread
{
    while(true)
    {
        if(!myQueue.empty())
        {
            Parent* p = myQueue.front();
            p->DoStuff();
            myQueue.pop();
         }
    }
    return 0;
}

What then happens is that the program crashes, saying "pure virtual method called", as if the inheritance/polymorphism isn't working correctly. I know the inheritance is set up correctly, because as I test I confirmed this works:

Child c;
Parent* p = &c;
p->DoStuff();

Any guidance greatly appreciated!

Was it helpful?

Solution

If you are passing the object to a worker thread, you can't create it on the stack. By the time the worker thread invokes it, the parent thread has likely left that function and destroyed the object. You need to dynamically allocate (perhaps via new) it in the parent thread and only free (delete) it in the worker thread after you're done with it.

As another note, you need locking around your queue accesses if the parent is able to enqueue a job while the worker is running.

OTHER TIPS

The error means that the object pointed to by p at the point of the call has type Parent. How it got that way depends on the code that you haven't shown.

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