Stencil
Stencil

Reputation: 1873

C++ - Calling overridden method in derived class from method base class

Let f1 be a virtual, non-abstract method of the class c and f2 be a method of the class c.
Let also c_derived be the derived class from the base class c.
Assume that f1 is overridden in c_derived. How can I call the method f1 (overridden) of c_derived- from the method f2 in c?
Possible work-around. Adding a function pointer parameter to the c::f2 parameter list, creating a wrapper c_derived::w of c::f2, and pass the function pointer of c_derived::f1 to c::f2 from the wrapper c_derived::w.
Is there, instead, a reasonable way to do it?

Upvotes: 2

Views: 3471

Answers (2)

skypjack
skypjack

Reputation: 50540

Despite the nice answer by Luchian Grigore, I'd like to point out that this idea is the one behind the template method pattern.

That pattern let the derived classes decide how to complete an algorithm implementation, either by offering a default solution in the form of a virtual method or no solution at all by using a pure virtual method.

In both the cases above mentioned, the f2 member invokes the right implementation of the f1 member as it follows:

f1();

Knowing the name of the solution one is applying usually is helpful.

Upvotes: 3

Luchian Grigore
Luchian Grigore

Reputation: 258608

This is tricky, but it can be done with some hacking:

void c::f2()
{
    f1();   // if f1 is overriden in a class deriving from c, 
            // the derived class version is called
}

To call base class version (c::f1), you need to fully qualify the call - c::fi().

Upvotes: 4

Related Questions