Calling Base Class Definition of Virtual Member Function with Function Pointer

Calling base class definition of virtual member function with function pointer

When you call a virtual method via a reference or a pointer you will always activate the virtual call mechanism that finds the most derived type.

Your best bet is to add an alternative function that is not virtual.

Passing virtual function pointer as argument of a Base Class function

Now that it's been clarified that create is infact pthread_create, you can have

class P
{
static void* do_job(void* self)
{
static_cast<P*>(self)->job();
return nullptr;
}
pthread_t thread;
public:
virtual void job() = 0;

void start()
{
pthread_create(&thread, nullptr, &P::do_job, this);
cout << "P::start()" << endl;

}
};

Pointer to a base virtual member function

You might define a non-virtual function real_g called from g so code

struct Base
{
void real_g() const {
std::cout << "Base" << std::endl;
}
virtual void g() const { real_g(); };
};

Then later in main

std::mem_fn(&Base::real_g)(d);

See wikipage on virtual method table, this C++ reference and the C++ standard n3337 or better. Read also a good C++ programming book and the documentation of your C++ compiler, e.g. GCC

See also this answer (explaining naively what are vtables, in simple cases)

Pointer to base virtual function vs direct call of base virtual function

From the C++ standard:

[expr.call]/1 For a call to a non-static member function, the postfix expression shall be an implicit (12.2.2, 12.2.3) or explicit class member access (8.2.5) whose id-expression is a function member name, or a pointer-to-member expression (8.5) selecting a function member; the call is as a member of the class object referred to by the object expression... If the selected function is non-virtual, or if the id-expression in the class member access expression is a qualified-id, that function is called. Otherwise, its final overrider (13.3) in the dynamic type of the object expression is called; such a call is referred to as a virtual function call.

Thus, there are only two cases where virtual dispatch is not performed for a call of a non-static member function: 1) the function is not virtual to begin with, or 2) the function is named with a qualified name, as in obj.Base::fn(). In all other cases - including the case of calling via a pointer-to-member - the final overrider is called.



Related Topics



Leave a reply



Submit