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;
}
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.
Output:
print derived class
need an explanation for this answer? contact us directly to get an explanation for this answer