11---
22title : " Virtual Functions"
3- ms.date : " 11/04/2016 "
3+ ms.date : " 09/10/2019 "
44helpviewer_keywords : ["functions [C++], virtual functions", "derived classes [C++], virtual functions", "virtual functions"]
55ms.assetid : b3e1ed88-2a90-4af8-960a-16f47deb3452
66---
@@ -21,6 +21,7 @@ using namespace std;
2121class Account {
2222public:
2323 Account( double d ) { _ balance = d; }
24+ virtual ~ Account() {}
2425 virtual double GetBalance() { return _ balance; }
2526 virtual void PrintBalance() { cerr << "Error. Balance not available for base type." << endl; }
2627private:
@@ -41,15 +42,15 @@ public:
4142
4243int main() {
4344 // Create objects of type CheckingAccount and SavingsAccount.
44- CheckingAccount * pChecking = new CheckingAccount ( 100.00 ) ;
45- SavingsAccount * pSavings = new SavingsAccount ( 1000.00 );
45+ CheckingAccount checking ( 100.00 );
46+ SavingsAccount savings ( 1000.00 );
4647
4748 // Call PrintBalance using a pointer to Account.
48- Account * pAccount = pChecking ;
49+ Account * pAccount = &checking ;
4950 pAccount->PrintBalance();
5051
5152 // Call PrintBalance using a pointer to Account.
52- pAccount = pSavings ;
53+ pAccount = &savings ;
5354 pAccount->PrintBalance();
5455}
5556```
@@ -121,8 +122,6 @@ int main() {
121122}
122123```
123124
124- ### Output
125-
126125``` Output
127126Derived::NameOf
128127Invoked by Base
@@ -150,4 +149,4 @@ Account *pAccount = pChecking; // Call Account::PrintBalance
150149pAccount->Account::PrintBalance (); // Explicit qualification.
151150```
152151
153- Both calls to ` PrintBalance ` in the preceding example suppress the virtual function-call mechanism.
152+ Both calls to ` PrintBalance ` in the preceding example suppress the virtual function-call mechanism.
0 commit comments