Polymorphism

Polymorphism means "many forms".

int main() {
	std::vector<Account> my_accounts;
	
	// this is sort of OK (except: "slicing" will occur)
	my_accounts.push_back(CheckingAccount(2000.0));
	
	std::cout << my_accounts.back().type() << std::endl;
	return 0;
}

Functions

void print_account_type(const Account& acct) {
	std::cout << acct.type() << std::endl;
}

int main() {
	...
	CheckingAccount checking(1000.0, 2.00);
	...
	print_account_type(checking); // Prints "Account"
	...
}


Usually you may use a variable of a derived type as though it has the base type because CheckingAccount is-an Account.

Dynamic Binding

To use it, we declare relevant member functions as virtual.

class Account{
public:
	...
	virtual std::string type() const { return "Account"; } 
};

class CheckingAccount : public Account {
public:
	...
	virtual std::string type() const { return "CheckingAccount"; }
};

virtual means that the function is essentially virtual and can be replaced by something else.