This blog is about providing theory as well as simple executable codes of different programming languages such as java, C, C++, and web programming, etc. This blog will be helpful to the IT students to learn about programming.

Wednesday, March 1, 2023

What is Virtual function? Write a program showing the example of virtual function.

 A virtual function is a member function in a base class that can be overridden in a derived class. When a virtual function is called using a pointer or reference to a base class object, the appropriate derived class function is called based on the type of the object pointed to or referenced.

Here is an example program showing the use of virtual function:

#include <iostream>
using namespace std;
class Shape {
   protected:
      int width, height;
   public:
      Shape(int w = 0, int h = 0) {
         width = w;
         height = h;
      }
      virtual int area() {
         cout << "Parent class area :" << endl;
         return 0;
      }
};
class Rectangle: public Shape {
   public:
      Rectangle(int w = 0, int h = 0): Shape(w, h) { }
      int area() {
         cout << "Rectangle class area :" << endl;
         return (width * height);
      }
};
class Triangle: public Shape{
   public:
      Triangle(int w = 0, int h = 0): Shape(w, h) { }
      int area() {
         cout << "Triangle class area :" << endl;
         return (width * height / 2);
      }
};
int main() {
   Shape *shape;
   Rectangle rec(10,7);
   Triangle  tri(10,5);
   shape = &rec;
   // call rectangle area
   shape->area();
   shape = &tri;
   // call triangle area
   shape->area();
   return 0;
}

In this program, we have a base class Shape with a virtual function area(), and two derived classes Rectangle and Triangle that override this function. In the main() function, we create objects of Rectangle and Triangle classes and assign their addresses to a pointer of type Shape. We call the area() function using the pointer, and the appropriate derived class function is called based on the type of object being pointed to.

No comments:

Post a Comment

If you have any doubts, please let me know

Slider Widget