Q:

What is the virtual function?

0

What is the virtual function?

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Answer:

When derived class overrides the base class function by redefining the same function. If a client wants to access redefined the method from derived class through a pointer from the base class object, then you must define this function in the base class as a virtual function.

Let see an example, where the derived class function is called by base class pointer using virtual keyword.

#include<iostream>
using namespace std;
//Base class
class base
{
public:
    virtual void print()
    {
        cout << "print base class" << endl;
    }
};
//Child class
class derived: public base
{
public:
    void print()
    {
        cout << "print derived class" << endl;
    }
};
int main(void)
{
    //derive class object
    derived d;
    
    //Base class pointer
    base *b = &d;
    
    // virtual function, binded at runtime
    b->print();
    
    return 0;
}

Output:

print derived class

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now