Did you like how we did? Rate your experience!

4.5

satisfied

46 votes

What are the applications of virtual functions in CPP?

Question: What are the applications of virtual functions in CPP? Virtual Functions allow late(runtime) binding of function/methods. Normally when methods are called which are part of an inheritance strategy, the version of which is determined at compile time. If the method is virtual, the version is determined at runtime based on what the object is. Heres (an/some) example(s) of what I mean: class A { // ... public: // ... virtual void drawMe() = }; class B : public A { // ... public: // ... virtual void drawMe(); }; class C : public B { // ... public: // ... virtual void drawMe(); }; class D : public A { // ... public: // ... virtual void drawMe(); }; A *ptrA = new C(); ptrA->drawMe(); In that example, you have 4 versions of drawMe(); - As version of drawMe is abstract(pure virtual) so has no implementation so what version of drawMe() gets called? As is not an option. Bs? Cs? The answer is Cs version because ptrA is instantiated as an object of type C but if it wasnt virtual, first off drawMe could not be abstract as the only way to make an abstract function in C++ is with a virtual function and assigning it to in the declaration. If it wasnt abstract, if it wasnt virtual, and if it had an implementation, the same scenario would result in the version of drawMe from A being executed. So lets say the following implementations were coded: void A::drawMe() { cout

100%
Loading, please wait...