Skip to main content

Posts

Showing posts with the label virtual function

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) { }   ...

When do we use virtual function? Differentiate early and late binding.

Virtual functions are used in object-oriented programming to achieve polymorphism. In particular, virtual functions are used in the following scenarios: When a base class pointer points to an object of the derived class, and we want to call a member function of the derived class through the base class pointer. This is known as runtime polymorphism, and it requires the use of virtual functions. When a base class has one or more functions that are intended to be overridden by derived classes. In this case, the base class should declare these functions as virtual, so that the derived classes can override them as needed. In general, virtual functions are used to provide a way for derived classes to customize the behavior of a base class, while still remaining a common interface with other classes in the inheritance hierarchy. This makes it easier to write code that can work with object of different derived classes, without having to know the details of each class's implementation. Earl...