Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling a virtual function statically through a function pointer

Please consider the following code.

#include <iostream>
#include <memory>

struct A {
  A() {}
  virtual void f() {
    std::cout << "A::f" << std::endl;
  }
private:
  A(const A&);
};

struct B : public A {
  virtual void f() {
    std::cout << "B::f" << std::endl;
    call(&A::f);
  }
private:
  void call(void (A::*aMethod)()) {
    // ...
    (static_cast<A&>(*this).*aMethod)();
    //(static_cast<A>(*this).*aMethod)();  -> not allowed to copy!
    // ...
  }
};

void main() {
  std::auto_ptr<B> b (new B);
  b->f();
}

This code recursively calls the same B::f method until it runs out of stack, while I would like the call method to call A::f. That is, it should call it statically as it would normally happen had I simply written:

struct B : public A {
  virtual void f() {
    std::cout << "B::f" << std::endl;
    // ...
    A::f();
    // ...
  }
};

The reason I want to have the call method is to factor some code before and after the 'static call' that is common to several methods with the same signature as f...

How can I statically call a virtual function decided at run-time?

like image 701
Xavier Nodet Avatar asked Dec 03 '10 13:12

Xavier Nodet


1 Answers

That's expected. The object expression is a Reference to the Base class A and hence virtual function mechanism (dynamic binding) is triggered as A::f is virtual.

Only the :: operator can supperess virtual function call mechanism.

$10.3/12- "Explicit qualification with the scope operator (5.1) suppresses the virtual call mechanism."

like image 62
Chubsdad Avatar answered Sep 21 '22 18:09

Chubsdad