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

。_饼干妹妹 提交于 2019-12-11 04:16:18

问题


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?


回答1:


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



回答2:


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

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

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



回答3:


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


来源:https://stackoverflow.com/questions/38010286/how-can-i-call-virtual-function-definition-of-base-class-that-have-definitions-i

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!