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.
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.
- class Base
- {
- int a;
- public:
- Base()
- {
- a = 1;
- }
- virtual void method()
- {
- cout << a;
- }
- };
- class Child: public Base
- {
- int b;
- public:
- Child()
- {
- b = 2;
- }
- virtual void method()
- {
- cout << b;
- }
- };
- int main()
- {
- Base *pBase;
- Child oChild;
- pBase = &oChild;
- pBase->method();
- return 0;
- }
No comments:
Post a Comment