3.6 Runtime Polymorphism
3.6 Runtime Polymorphism
Function Overriding
polymorphism.
The “virtual”-ity of the member function continues along the inheritance
chain.
A class that contains a virtual function is referred to as a polymorphic class.
#include <iostream> void main() {
using namespace std; base b1;
class base b1.show(); // base - (s.b.)
{
public: derived d1;
virtual void show() { d1.show(); // derived – (s.b.)
cout << “base\n”;
} base *pb = &b1;
}; pb->show(); // base - (d.b.)
class derived : public base
{ pb = &d1;
public: pb->show(); // derived (d.b.)
void show() { }
cout << “derived\n”; /* Here,
} s.b. = static binding
}; d.b. = dynamic binding */
#include <iostream> class d2 : public base
using namespace std; {
class base public:
{ void show() {
public: cout << “derived-2\n”;
virtual void show() }
{ };
cout << “base\n”;
} void main()
}; {
base *pb;
class d1 : public base d1 od1;
{ d2 od2;
public: pb = &od1;
void show() pb->show();
{
cout << “derived-1\n”; pb = &od2;
} pb->show();
}; return 0;
}
Virtual Destructors
It ensures that the derived class destructor is called when a base class
Helps to guarantee that a derived class will provide its own redefinition.
We can still create a pointer to an abstract class
hierarchy.
Run-time polymorphism is not automatically activated in C++.
We have to use virtual functions and base class pointers to enforce and
Note:-