Programming with Passion

Make the best out of everything.

Friday, 8 April 2016

What are virtual functions and what is its use?

What are virtual functions and what is its use?
[This is a sure question in not just C++ interviews, but any other OOP language interviews. Virtual functions are the important concepts in any object oriented language, not just from interview perspective. Virtual functions are used to implement run time polymorphism in c++.]
Virtual functions are member functions of class which is declared using keyword 'virtual'. When a base class type reference is initialized using object of sub class type and an overridden method which is declared as virtual is invoked using the base reference, the method in child class object will get invoked.
  1. class Base
  2. {
  3. int a;
  4. public:
  5. Base()
  6. {
  7. a = 1;
  8. }
  9. virtual void method()
  10. {
  11. cout << a;
  12. }
  13. };
  14.  
  15. class Child: public Base
  16. {
  17. int b;
  18. public:
  19. Child()
  20. {
  21. b = 2;
  22. }
  23. virtual void method()
  24. {
  25. cout << b;
  26. }
  27. };
  28.  
  29. int main()
  30. {
  31. Base *pBase;
  32. Child oChild;
  33. pBase = &oChild;
  34. pBase->method();
  35. return 0;
  36. }
In the above example even though the method in invoked on Base class reference, method of the child will get invoked since its declared as virtual.

No comments:

Post a Comment