Posted Joe Chu cpp3 minutes read (About 519 words)0 visits
Virtual Function
Virtual function, pure virtual function, abstract class
Virtual function
A virtual function is a member function in the base class that we expect to redefine in derived classes.
override identifier is not necessary but highly recommended to use to avoid bugs. When using override, the compiler will display related error messages when bugs exists. For examples:
classDerived : public Base { public: Derived() {} // void print() override{ // std::cout << "Derived print()\n"; // } };
intmain(){ Base* b = newDerived(); b->print(); // Base print() delete b; }
You may hear of another terminology called dynamic dispatch. By declaring a method as virtual, the C++ compiler uses a vtable to define the name-to-implementation mapping for a given class as a set of member function pointers. However, one can use explicit scoping, rather than dynamic dispatch, to ensure a specific version of a function is called.
intmain(){ Base* b = newDerived(); b->Base::foo(); delete b; }
1 2 3 4 5
Base constructor called Derived constructor called Base foo() Derived deconstructor called Base deconstructor called
Pure virtual function
A pure virtual function is a function defined in base class but has no implementation. It requires its derived classes to implement their own versions of this function. A class containing pure virtual function(s) is called abstract class.
1 2 3 4 5 6
classBase { public: Base() {} virtualvoidprint()= 0; // pure virtual function };
A abstract class can not be instantiate. If the derived class does not implement the pure virtual function, it makes the derived class an abstract class as well. We can neither instantiate the derived class.