Sunday, April 24, 2011

Polymorphism and Virtual Function in C++

Virtual function syntax:
virtual void func(int i){};

Pure virtual function syntax:
virtual void func(int i) = 0;

If a class contains at least one pure virtual member, it is an abstract class - we cannot instantiate an object of an abstract class. However, we can create a pointer that points to such a class. Suppose

class myAbsClass{
virtual void func(int i) = 0;
}

class myChildClass: public myAbsClass{
void func(int i) {return 1};
}

Then we can do
myAbsClass* pointer1;
pointer1 = new myChildClass;

Polymorphism makes coding more flexible and efficient. For example, suppose there are more than one (non-abstract) child classes, and each of them has different implementations of the virtual function in the parent class. If we want to write a function that requires the returned value of such functions, we do not have to write it multiple times, but only need to write it so that it takes the abstract pointer as an input.

No comments:

Post a Comment