Hinweis
Für den Zugriff auf diese Seite ist eine Autorisierung erforderlich. Sie können versuchen, sich anzumelden oder das Verzeichnis zu wechseln.
Für den Zugriff auf diese Seite ist eine Autorisierung erforderlich. Sie können versuchen, das Verzeichnis zu wechseln.
C++ Specific —>
A virtual function is a member function that you expect to be redefined in derived classes. When you refer to a derived class object using a pointer or a reference to the base class, you can call a virtual function for that object and execute the derived class's version of the function.
END C++ Specific
Example 1
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
The virtual keyword is needed only in the base class's declaration of the function; any subsequent declarations in derived classes are virtual by default.
A derived class's version of a virtual function must have the same parameter list and return type as those of the base class. If these are different, the function is not considered a redefinition of the virtual function. A redefined virtual function cannot differ from the original only by return type.