1
votes

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?

3
How to create a Minimal, Complete, and Verifiable example stackoverflow.com/help/mcveRichard Critten
@RichardCritten Useful in general, but to be fair, the OP's description of the code is good enough to understand as-is.Angew is no longer proud of SO

3 Answers

4
votes

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);
}
1
votes

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

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

  B b;
  b.A::foo();
1
votes

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(); }
}