statquant statquant - 2 months ago 7
C++ Question

Why do I have to implement a virtual function in a derived class if I want to use the base class implementation

I have an pure virtual base class and a derived class. I know I am allowed to implement a virtual (not pure) method in the base class.
What I do not understand is why I

HAVE
to also implement the same method in the derived class if what I want is simply to use the base implementation:

#include <iostream>

using namespace std;

class Abstract {
public:
int x;
Abstract(){
cout << "Abstract constructor" << endl;
x = 1;
}
virtual void foo() = 0;
virtual void bar(){
cout << "Abstract::bar" << endl;
}
};

class Derived : Abstract {
public:
int y;
Derived(int _y):Abstract(){
cout << "Derived constructor" << endl;
}
virtual void foo(){
cout << "Derived::foo" << endl;
}
virtual void bar(){
Abstract::bar();
}
};

int main()
{
cout << "Hello World" << endl;
Derived derived(2);
derived.foo();
derived.bar(); //HERE I HAVE TO DEFINE Derived::bar to use it
return 0;
}

Answer

You don’t have to do that. You can do the following:

class Derived : public Abstract {

That way, you can use the public methods from the base class.

Comments