c++ - Why do I have to implement a virtual function in a derived class if I want to use the base class implementation -
i have pure virtual base class , derived class. know allowed implement virtual (not pure) method in base class. not understand why have
implement same method in derived class if want use 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 have define derived::bar use return 0; }
you don’t have that. can following:
class derived : public abstract {
that way, can use public methods base class.
Comments
Post a Comment