Function Overriding in C++ with Example



The member function can also be used in a derived class, with the same name as in the base class. So that calls in program work the same way for object of both base and derived class.

Example:

Function Overriding

#include<iostream.h>
#include<conio.h>
class A
               {
                              public:
                              void get()
                              {
                                             cout<<”Base Class”;
}
               };
class B : public A
               {
                              public:
                              void get()
                              {
                                             cout<<”Derived Class”;
}
               };
void main()
{
               clrscr();
               B ba;
               ba.get();
               ba.A::get();          //Late Binding
               getch();
}
Output:
Derived Class
Base Class

Late Binding
Choosing functions during execution time is known as late binding or dynamic linkage. Late binding needs some overhead but provides enhanced power as well as flexibility. The late binding is implemented via virtual functions. An object of a class need to be declared either as a pointer to a class or a reference to a class.

No comments:

Post a Comment