Polymorphism
Function Overriding
- Suppose, the same function is declared in both the derived class and the base class.
- Now if we call this function using the object of the derived class, which function will be
called ??
- The function of the derived class is executed.
- This is known as function overriding in C++.
- The function in derived class overrides the function in base class.
Pointers - variables that store address of other variables.
int a = 5;
int* p = &a;
char c = 'A';
char* p1 = &c;
- Similarly we can make pointers for user-de ned datatypes (i.e. classes).
- In C++, we can declare a pointer that points to the base class as well as derive class.
- One of the key features of class inheritance is that a pointer to a derived class is type-
compatible with a pointer to its base class.
Virtual Functions:
- But, we just discovered that a base pointer, even when it is made to contain the
address of a derived class, always executes the function in the base class.
- The compiler simply ignores the contents of the pointer and chooses the member
function that matches the type of the pointer.
- How do we then achieve polymorphism? It is achieved using what is known as 'virtual'
functions.
- When we use the same function name in both the base and derived classes, the
function in base class is declared as virtual using the keyword virtual preceding its
normal declaration.
fi
- When a function is made virtual, C++ determines which function to use at run time
based on the type of object pointed to by the base pointer, rather than the type of the
pointer. Thus, by making the base pointer to point to di erent objects, we can execute
di erent versions of the virtual function.
- A virtual function is a member function in the base class that we expect to rede ne in
derived classes.
- Basically, a virtual function is used in the base class in order to ensure that the function
is overridden. This especially applies to cases where a pointer of base class points to
an object of a derived class.
ff
ff
fi