1

Suppose I have the following code

class A{
public:
   void f1()
   {
       /* 
        * Other functions that happen here.
        * These calls needs to be made at A's f1() function
        * And cannot be in derived class.
        */    
       f2();
   }
  
   virtual void f2()
   {
       std::cout << "I am base class" << std::endl;
   }
};

class B : A 
{
public: 
    void f2()   
    {
         std::cout << "I am derived class" << std::endl;
    } 
  
    void f3()
    {
        A::f1();
    }
};

int main()
{
    B b;
    b.f3();
    return 0;
}

The output above is

I am derived class

The limitation I have here is that I can't change class A in any way. Another limitation is that f2() needs to be called through f1(). A::f3() cannot call f1(). The call to f1() needs to be made to A since A's f1() does other things and B cannot override it.

Is there a way to force A::f2() be called when B::f3() is called? In other words, when we ask for the base version, how do we enforce all other functions called within the base class, to use the base version. In this example, that would be f2().

The question marked as duplicate is simply asking to call a parent function from a derived function with no other functions in the called function that overwritten.

Please note that a static cast of A to call f1 will result in the derived class's f2 function to be called.

Hadi
  • 945
  • 3
  • 10
  • 31
  • _Is there a way to force A::f2() be called when B::f3() is called?_ Yes. Replace `A::f1();` by `A::f2();` in `B::f3();`. [Demo on coliru](http://coliru.stacked-crooked.com/a/4fa00b90b94d83e1) – Scheff's Cat Jul 14 '22 at 18:23
  • But I need it be called from A. Let me modify the question. – Hadi Jul 14 '22 at 18:24
  • 3
    Change `f1` to call `A::f2`; if you can't change `A`, then no, you can't. – ChrisMM Jul 14 '22 at 18:26
  • I updated the question. The original version didn't show what I needed. I have two limitations. I basically need the base class to call its base versions when there derived class has a derived version. – Hadi Jul 14 '22 at 18:28
  • So, if you need A::f1 to call A::f2, replace the line in A::f1 `f2()` to be `A::f2()` – franji1 Jul 14 '22 at 18:35
  • The point is that A is also doing other things, then it needs to fall f2(). – Hadi Jul 14 '22 at 18:43
  • 1
    1) Don't override f2 in B. or 2) Make a temporary A that is a sliced copy of the current object and do the operation using that. (Wouldn't preserve any mutations.) – Avi Berger Jul 14 '22 at 18:43
  • 2
    What you are asking to do is basically impossible in the way you are describing. Maybe explain what problem you are actually having, so people can suggest ways to fix it. This sounds to me like an [xy problem](https://en.wikipedia.org/wiki/XY_problem). – ChrisMM Jul 14 '22 at 18:45
  • I think Im pretty clear on the problem I am having. I have limitations and perhaps the answer is that its impossible.. – Hadi Jul 14 '22 at 18:47

0 Answers0