Submit Your Site For Free!

Email Address:
* URL:
*
*Indicates Mandatory Field

Terms & Conditions

CProgramTrends
FlashNewz
DevWebPro








Let's Get Virtual, Virtual...

By Bryan Young
Expert Author
Article Date: 2010-07-15

Even though I have used virtual functions in the past, I never really understood them. They always seemed just beyond the realm of what I believed I could do with a strict typing language like C++. Of course, I had just a vague grasp on polymorphism at the time.

Virtual functions work by taking a function in a base class and allowing derived classes to override its functionality. This sounds an awful lot like a simple function overload, but it is most definitely different. Suppose you have two classes like these.

class Parent

{
void myPrint() {cout << "This is the Parent class!" << endl;}
};

class Child : public Parent
{
void myPrint() {cout << "This is the Child class!" << endl;}
};

In your main function, making these calls:

int main()

{
Parent *p, *c;

p = new Parent();
c = new Child();

p->myPrint();
c->myPrint();

return 0;
}

yields this output:

This is the Parent class!

This is the Parent class!

Declaring the myPrint function as virutal in the Parent class, solves this problem by allowing the Child class version of myPrint to override the Parent class version.

virtual void myPrint() {cout << "This is the Parent class!" << endl;}

When you run the program again after making this change, you get the desired output.

This is the Parent class!

This is the Child class!

The primary difference between a virtual function and a non-virtual function is the point in time when the function is bound. In non-virtual functions, static binding takes place. This is where the function is set in stone as being from the class it is set to. Virtual functions allow dynamic binding to take place. This is where the function is not truly defined until runtime. Virtual functions allow pointers of the same type to point at different objects, while still using the proper functions of what the pointer is really pointing at.



About the Author:
Bryan Young is a staff writer for WebProNews.



Newsletter Archive | Article Archive | Submit Article | Advertising Information | About Us | Contact

C Programming Trends is an iEntry, Inc. ® publication - All Rights Reserved Privacy Policy and Legal