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
This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
By continuing to use this site, you are consenting to our use of cookies.