Calling a virtual function for a specific object class in C ++

I need to call a function from the declaration type on some object outside the class. I made a small code example and set the desired behavior as comments, since I don’t know exactly how to set this :)

template<typename T> void hun(T* obj, class C* c) { //do some checking on c if(some conditions from c are true) { //call fun from T ignoring it virtual } } struct A { virtual void fun(){}; virtual void gun(class C* c) { //do something specific to A hun(this, c); //here call fun from A even if real type of this is B }; } struct B : public A { void fun(){}; void gun(class C* c) { //do something specific to B hun(this, c);//here call fun from B even if real type of this is something derived from B }; } 

Is it possible to achieve this behavior?

I know that I can call fun() from within the class using A::fun() or B::fun() , but the check from hun() is common to all classes, and I don't want to pollute gun() this code .

+4
source share
1 answer

(Probably already answered somewhere else.)

You can explicitly call one override of a virtual function using an identifier with qualifications. The qualified identifier for a member function is of the form my_class::my_function .

For reference, see C ++ Standard [expr.call] / 1:

If the selected function is not virtual, or if the id expression in the class is a member access expression, this is the qualification identifier that calls this function. Otherwise, its final bypass (10.3) to the dynamic type of the expression of the object.

Example

 template<typename T> void hun(T* obj, class C* c) { //do some checking on c if(some conditions from c are true) { //call fun from T ignoring it virtual obj->T::fun(); // T::fun is a qualified-id } } struct A { virtual void fun(){}; virtual void gun(class C* c) { //do something specific to A hun(this, c); //here call fun from A even if real type of this is B }; }; // note: semicolon was missing struct B : public A { void fun(){}; void gun(class C* c) { //do something specific to B hun(this, c);//here call fun from B even if real type of this is something derived from B }; }; 
+8
source

All Articles