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?
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);
}
You can specify the class scope explicitly when calling the function:
class A { /* Abstract class */ };
class B : public A {}
B b;
b.A::foo();
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(); }
}