Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass by value to virtual methods

I have a question on pass-by-value object construction and virtual methods.

I have a virtual method like this:

typedef boost::function1<void, void*> Task

class ITaskPool
{
    //......

    virtual AddTask(Task task) = 0;
};

And then an implementation like

class TaskPool : public ITaskPool
{
    //......

    AddTask(Task task);
};

If I use it like this;

void MyFunc(void* arg)
{

}

int main()
{
    TaskPool tp;
    tp.AddTask(&MyFunc); 
}

Will a Task object be created twice, once for when it is passed to the virtual method, and another when it is passed to the method of the derived class?

Thanks

like image 923
KaiserJohaan Avatar asked Jan 29 '26 10:01

KaiserJohaan


2 Answers

Just one copy would be created. When you declare a function virtual, method of that derived class is called through dynamic binding. Its not the case that first method A is called and then method B is called. COmpiler decides at run time which method to call.

Polymorphism and Dynamic Binding

like image 164
Coding Mash Avatar answered Jan 30 '26 23:01

Coding Mash


Your code is wrong (missing return types), but no, only one copy is involved. I think you got the wrong idea about polymorphism. It's not like the base class method is called first, and then gets forwarded to the derived class. TaskPool::AddTask is directly called through dynamic dispatch (if it's called polymorphically).

like image 45
Luchian Grigore Avatar answered Jan 31 '26 00:01

Luchian Grigore