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?
Asked
Active
Viewed 3,235 times
2

Stencil
- 1,833
- 1
- 17
- 19
-
It's c#, I know, but have you tried calling base.f1()? – Graham Bass Nov 18 '15 at 23:09
-
Duplicate? Actually, Is this not the droid you're looking for? http://stackoverflow.com/questions/357307/how-to-call-a-parent-class-function-from-derived-class-function – Graham Bass Nov 18 '15 at 23:13
-
@GrahamBass from the question, he wants to call the derived version from the base method. So just a simple call would do it... – Luchian Grigore Nov 18 '15 at 23:16
-
That inversion of the numbers f was a little confusing, given the pattern established for class. Wouldn't this violate SOLID principles? Seems like a base class should not be aware of or dependent on derivatives? – Graham Bass Nov 18 '15 at 23:19
-
Why is there a question in this question? It reads to me like a complicated way of asking nothing. For the simple meaning of the question, you just call f1(). That is how virtual functions work. But if you implied a third class derived from `c_derived` and you don't want the normal action of virtual, you can directly call `c_derived::f1()` – JSF Nov 18 '15 at 23:46
-
@JSF it is a rigorous question to ask nothing for an OOP-trained programmer who frequently works with OOP, but to ask something relevant for a programmer which is not used to OOP who wants to get response to problems after showing thoughts and effort – Stencil Nov 19 '15 at 08:47
2 Answers
4
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()
.

Luchian Grigore
- 253,575
- 64
- 457
- 625
3
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.

skypjack
- 49,335
- 19
- 95
- 187