0% found this document useful (0 votes)
47 views2 pages

Virtural Funvtion

A virtual function allows a derived class to override a function declared in the base class. When calling a virtual function through a base class pointer, the version from the derived class will be invoked due to runtime polymorphism. For example, a base class A declares a virtual function show() that prints member a. Class B inherits from A, overrides show() to print member b. When show() is called on a base class pointer pointing to a B object, B's version is called instead of A's.

Uploaded by

Karan Tyagi
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
47 views2 pages

Virtural Funvtion

A virtual function allows a derived class to override a function declared in the base class. When calling a virtual function through a base class pointer, the version from the derived class will be invoked due to runtime polymorphism. For example, a base class A declares a virtual function show() that prints member a. Class B inherits from A, overrides show() to print member b. When show() is called on a base class pointer pointing to a B object, B's version is called instead of A's.

Uploaded by

Karan Tyagi
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 2

What is virtual function? Explain with an example.

A virtual function is a member function that is declared within a base class and redefined by a derived class. To create virtual function, precede the functions declaration in the base class with the keyword virtual. When a class containing virtual function is inherited, the derived class redefines the virtual function to suit its own needs. Base class pointer can point to derived class object. In this case, using base class pointer if we call some function which is in both classes, then base class function is invoked. But if we want to invoke derived class function using base class pointer, it can be achieved by defining the function as virtual in base class, this is how virtual functions support runtime polymorphism. Consider following program code: Class A { int a; public: A() { a = 1; } virtual void show() { cout <<a; } }; Class B: public A { int b; public: B() { b = 2; } virtual void show() { cout <<b;

} }; int main() { A *pA; B oB; pA = &oB; pA->show(); return 0; }

You might also like