Еще один вопрос:
Virtual function — в MSDN есть такой пример:
// deriv_VirtualFunctions.cpp
// compile with: /EHsc
#include <iostream>
using namespace std;
class __declspec(dllexport) Account
{
public:
Account( double d ); // Constructor.
virtual double GetBalance(); // Obtain balance.
virtual void PrintBalance(); // Default implementation.
private:
double _balance;
};
// Implementation of constructor for Account.
Account::Account( double d )
{
_balance = d;
}
// Implementation of GetBalance for Account.
double Account::GetBalance()
{
return _balance;
}
// Default implementation of PrintBalance.
void Account::PrintBalance()
{
cerr << "Error. Balance not available for base type."
<< endl;
}
class __declspec(dllexport) CheckingAccount : public Account
{
public:
void PrintBalance();
};
// Implementation of PrintBalance for CheckingAccount.
void CheckingAccount::PrintBalance()
{
cout << "Checking account balance: " << GetBalance();
}
class __declspec(dllexport) SavingsAccount : public Account
{
public:
void PrintBalance();
};
// Implementation of PrintBalance for SavingsAccount.
void SavingsAccount::PrintBalance()
{
cout << "Savings account balance: " << GetBalance();
}
void main()
{
}
The PrintBalance function in the derived classes is virtual because it is declared as virtual in the base class, Account. To call virtual functions such as PrintBalance, code such as the following can be used:
// Create objects of type CheckingAccount and SavingsAccount.
CheckingAccount *pChecking = new CheckingAccount( 100.00 );
SavingsAccount *pSavings = new SavingsAccount( 1000.00 );
// Call PrintBalance using a pointer to Account.
Account *pAccount = pChecking;
pAccount->PrintBalance();
// Call PrintBalance using a pointer to Account.
pAccount = pSavings;
pAccount->PrintBalance();
In the preceding code, the calls to PrintBalance are identical, except for the object pAccount points to.
Механизм понятен, не понятно назначение. А зачем может понадобится вызывать функцию класса через указатель на предка класса ? То есть зачем делать так:
Account *pAccount = pChecking;
pAccount->PrintBalance();
А вот так:
pChecking->PrintBalance();
что не пойдет ?
Поясните, ГДЕ ВЫГОДНО использовать виртуальные функции ?