uray
uray

Reputation: 11562

Does a pointer to a virtual function still get invoked virtually?

Will a function pointer to a class member function which is declared virtual be valid?

class A {
public:
    virtual void function(int param){ ... };
}

class B : public A {
    virtual void function(int param){ ... }; 
}

//impl :
B b;
A* a = (A*)&b;

typedef void (A::*FP)(int param);
FP funcPtr = &A::function;
(a->*(funcPtr))(1234);

Will B::function be called?

Upvotes: 6

Views: 213

Answers (4)

BЈовић
BЈовић

Reputation: 64203

The best test for that thing is to make the methods in the class A a pure virtual method. In both cases (with or without pure virtual methods), B::function will be called.

Upvotes: 0

Vladimir Ivanov
Vladimir Ivanov

Reputation: 43088

The function will be called, as you just try to invoke inherited function.

Upvotes: 0

Matthieu
Matthieu

Reputation: 4620

Yes. Valid code to test on codepad or ideone :

class A { 
public: 
    virtual void function(int param){
      printf("A:function\n");
    }; 
};

class B : public A { 
public:
    virtual void function(int param){
      printf("B:function\n");
    };  
}; 

typedef void (A::*FP)(int param);

int main(void)
{
  //impl : 
  B b; 
  A* a = (A*)&b; 

  FP funcPtr = &A::function; 
  (a->*(funcPtr))(1234);
}

Upvotes: 4

Alexandre C.
Alexandre C.

Reputation: 56956

Yes. It also works with virtual inheritance.

Upvotes: 2

Related Questions