Posted by Muhammad Ali Shah on 1999-09-12
>>Okay a virtual function is a function that can be
>>declared and defined in a base class to have a
>>specific functionality and then you can define the
>>function differently in a derived class to have a
>>separate behavior than its base class.
I had been seeking the answer and found some thing quite different from what
you have said. This mail is not to show off my knowledge or let somebody
down. I didn't know the answer until I read your mail. But after reading
this mail I did a simple experiment. I defined a base class with a member
function show() and then derived a class with a member function of the same
name, ie. show(). It worked perfectly well and I had not used the keyword
virutal!
I thought then why do we have this keyword? After browsing Visual C++ help,
I arrived at the following example. Please read it and clear any
misconceptions. I may be wrong. But this is what I know at present. Sorry,
if my style offends you - but learning is what we are here for - I apologize
again, in advance, if it hurts somebody.
A virtual function is used when we want to use pointer to objects. A pointer
to an object of base class can call a function in derived class by using the
word virtual. Please see the example below.
class WageEmployee
{
public:
virtual float computePay();
};
class SalesPerson : public WageEmployee
{
public:
float computePay();
};
You can execute different versions of computePay( ) depending on the type of
object you're calling it for.
Example 2
WageEmployee aWorker;
SalesPerson aSeller;
WageEmployee *wagePtr;
wagePtr = &aWorker;
wagePtr->computePay(); // call WageEmployee::computePay
wagePtr = &aSeller;
wagePtr->computePay(); // call SalesPerson::computePay
Correct me if I am wrong. Regards from Pakistan...
Muhammad Ali Shah
BCS IV - FAST Institute of Computer Science, Karachi
Previous post | Next post | Timeline | Home