Re: Virtual functions
"Wilson" writes:
hi, i am trying to understand virtual functions, both how to create
them and how or when to use them - how they can be used to improve a
program. Below is a very simple program which i quickly made using
information gathered from a book on the subject, however this simply
returns a blank space. please help both on this program and anything
else related to virtual functions.
wilson
#include <cstdio>
#include <cstdlib>
#include <iostream>
using namespace std;
class account
{
public:
int balance, number;
int function() { cout << balance; }
};
class checking : public account
{
public:
int balancechecking;
You are off to a bad start. The balance should be a member of the base
function.
<snip>
Take a look at this. I am sure you can see how things such as service
charge and interest rate could be made a part of the class, for simplicity I
coded these constants in the functions. The order of doing things in main
was dictated by the order of testing,, which is not representative of an end
user application.
#include <iostream>
using namespace std;
class Acct
{
public:
virtual void add_int() = 0;
void show() { cout << balance << endl;}
protected:
double balance;
};
//----------------
class Checking : public Acct
{
public:
Checking(double bal) {balance = bal;}
void add_int() {balance -= 15;} // monthy "service" fee
private:
};
//--------------------
class Savings : public Acct
{
public:
Savings(double bal) {balance = bal;}
void add_int() {balance *= 1.01;}
private:
};
//=====================
int main()
{
Acct* arr[2];
arr[0] = &Checking(256);
arr[0] -> add_int();
arr[0] -> show();
arr[1] = &Savings(1024);
arr[1] -> add_int();
arr[1] -> show();
cin.get();
cin.get();
}