Search code examples
c++functionoverridingvirtual

Can in C++ override a virtual method by calling a method from a private instantiated class without reimplementing it?


sorry updated

I have a class A that overrides many methods from another class B and beside it has an instance of the class B from which I want the methods to be called. B is an interface with virtual methods so it has an implementation passed to me via pointer i.e. class B

class B{
public:
  virtual int f1(int x);
  virtual int f2(int x)
}

then I have other classes which implements B, let's say C, D and E which also have other interfaces.

then I have the class A which has a pointer to a class that implements B besides other thing.

I need to override the methods in a manner like the following one

and class A

class A:
  public B
{
private:
  B* b;
public:
  A(B* _b){
    b = _b;
  }
  int f1(int x) override
  {
    return b->f1(x);
  }
      
  int f2(int y) override
  {
    return b->f2(y);
  }
}

Is it possible to avoid the overriding of each method by allowing the compiler to call the methods from the implementation?


Solution

  • If you want to call f1() and f2() on the member variable, then no. There is no automatic mechanism to tell the compiler that calls to A::f1() should be forwarded to b->f1().