How can I call virtual function definition of base class that have definitions in both abstract base class and derived class in C++?
Asked Answered
R

3

1

We can't create an object of an abstract class, right? So how can I call a virtual function which has definition in both abstract base class and derived class? I want to execute the code in abstract base class but currently, I am using derived class's object.

class T
{
   public:
   virtual int f1()=0;
   virtual int f2() { a = 5; return a }
}
class DT : public T
{
   public:
   int f1() { return 10; }
   int f2() { return 4; }
}

int main()
{
    T *t;
    t = new DT();
    ............
}

Is there any way I can call the base class function using the object t? If it is not possible, what should I need to do to call the base class function?

Rozamond answered 24/6, 2016 at 9:41 Comment(2)
How to create a Minimal, Complete, and Verifiable example stackoverflow.com/help/mcveAlbertoalberts
@RichardCritten Useful in general, but to be fair, the OP's description of the code is good enough to understand as-is.Felicitasfelicitate
F
4

Just like you would call any other base class implementation: use explicit qualification to bypass the dynamic dispatch mechanism.

struct AbstractBase
{
  virtual void abstract() = 0;

  virtual bool concrete() { return false; }
};

struct Derived : AbstractBase
{
  void abstract() override {}

  bool concrete() override { return true; }
};

int main()
{
  // Use through object:
  Derived d;
  bool b = d.AbstractBase::concrete();
  assert(!b);

  // Use through pointer:
  AbstractBase *a = new Derived();
  b = a->AbstractBase::concrete();
  assert(!b);
}
Felicitasfelicitate answered 24/6, 2016 at 9:45 Comment(1)
@Rozamond That doesn't even compile. Perhaps it should have been T *t;? If so, just do t->T::f2(); and edit your question to have correct code.Felicitasfelicitate
P
1

You can specify the class scope explicitly when calling the function:

  class A { /* Abstract class */ };
  class B : public A {}

  B b;
  b.A::foo();
Pleiades answered 24/6, 2016 at 9:45 Comment(0)
P
1

If the abstract base class has some code, then just call BaseClassName::AbstractFunction()

class Base
{
    virtual void Function()  {}
}

class Derived : Base
{   
    virtual void Function() { Base::Function(); }
}
Polybasite answered 24/6, 2016 at 9:46 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.