Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations wOOdy-Soft on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Virtual Definitions

Status
Not open for further replies.

Stopher

Programmer
Jan 12, 2002
29
US
can anyone explain what exactly this means?

virtual void myfunction(void);
 
It's a bit tricky to understand if you don't know about OO.

Suppose you have a class A with that virtual function:
class A {
...
...
virtual void myfunction(void);
}

And a derived class B:
class B : public A
...
...
void myfunction(void);
}

And a derived class C:
class C : public A
...
...
void myfunction(void);
}


Now if you do this:

void test(void) {
B clsB;
C clsC;

A* ptrA = NULL;

ptrA = &clsB;
ptrA->myfunction; //Method in class B will be executed.

ptrA = &clsC;
ptrA->myfunction; //Method in class C will be executed.

ptrA = new A;
ptrA->myfunction; //Method in class A will be executed.

delete ptrA;
}


Now this might seem a bit strange (especially in such a simple example) but actually this is one of the strongest points of OOP. Imagine for example having a collection of different types of employees (i.e. manager, secretary etc.) all derived from a base class of employee having a virtual function which calculates for example their salary. You can loop through the collection with a base class pointer and rest assured that the correct salary calculation will be done (a more classic example...).
Greetings,
Rick
 
virtual functions are the mechanism in C++ that implements Polymorphism

google Polymorphism

-pete
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top