You are on page 1of 4
Virtual function and pure virtual funtion in C++ < January 23, 2020 Virtual Functions Virtual functions in C++ use to create a list of base class pointers and call methods of any of the derived classes without even knowing kind of derived class object. Virtual functions are resolved late, at runtime. The main use of virtual function is to achieve Runtime Polymorphism. Runtime polymorphism can be achieved only through a pointer (or reference) of base class type. Also, a base class pointer can point to the objects of base class as well as to the objects of derived class. In above code, base class pointer ‘b’ contains the address of object ‘d’ of derived class. Example Code #includeciostream> using namespace std; class 8 { public: virtual void s() { cout<<" In Base \ oH class D: public B { public: void s() { cout<<"In Derived \n"; ub int main(void) { Dd; // An object of class D B *b- &d; // A pointer of type BY pointing to d b->s(); // prints "D::s() called" return 9; Output In Derived Pure Virtual Functions A pure virtual function is a virtual function in C++ for which we need not to write any function definition and only we have to declare it. It is declared by assigning 0 in the declaration. ‘An abstract class is a class in C++ which have at least one pure virtual function. Abstract class can have normal functions and variables along with a pure virtual function, Abstract class cannot be instantiated, but pointers and references of Abstract class type can be created Abstract classes are mainly used for Upcasting, so that its derived classes can use its interface. If an Abstract Class has derived class, they must implement all pure virtual functions, or else they will become Abstract too. We can't create object of abstract class as we reserve a slot for a pure virtual function in Vtable, but we don't put any address, so Vtable will remain incomplete. Example Code #includeciostream> using namespace std; class B ( public: virtual void s() = @; // Pure Virtual Function h class D:public B { public: void s() { cout << “Virtual Function in Derived class\n"; int main() { B Yb; D dobj; b = &dobj; b-»s()5 Output Virtual Function in Derived class Enter your comment. Popular posts from this blog Explain inheritance and types with program January 23, 2020 Inheritance in C++ Inheritance is one of the feature of Object Oriented Programming System(OOPs), it allows the child class to acquire the properties (the data members) and functionality (the member functions) of parent class. What is child class? READ MORE G Powered by Blogger ‘Theme images by Michael Ekan < SANGEETSARGAM SAGAR Archive v Report Abuse

You might also like