// Bank account objects in C - is overloading enough? #include #include typedef struct accstruct * account; struct accstruct { int balance; }; // constructor account newaccount(int bal) { account A = (account)malloc(sizeof(struct accstruct)); A->balance = bal; // set init balance return A; } ////////////// MAXIMIZE CODE REUSE // in order to show difference between overloading and dyn dispatch, the // dynamic TYPE of something can't be known at compile time. struct checkingstruct { int balance; int fee; }; typedef struct checkingstruct* checking; struct savingsstruct { int balance; int bonus; }; typedef struct savingsstruct* savings; checking newchecking(int bal, int fee) { checking A = (checking)malloc(sizeof(struct checkingstruct)); A->balance = bal; A->fee = fee; return A; } savings newsavings(int bal, int bn) { savings A = (savings)malloc(sizeof(struct savingsstruct)); A->balance = bal; A->bonus = bn; return A; } // no need for tag here? is overloading enough (doesn't exist in C, but // can add easily) // What is operator overloading: disambiguate which version of f to call // at compile time. // want: list of accounts, some checking, some savings, want to perform // a deposit operation on all accounts. int inquiry(account A) { return A->balance; } void deposit(account A, int amt) { A->balance += amt; } void withdraw(account A, int amt) { if (amt<=A->balance) A->balance -= amt; } int moremoney(account A, account B) { return (A->balance > B->balance); } void withdraw(checking A, int amt) { amt += A->fee; withdraw((account)A,amt); } void deposit(savings A, int amt) { A->balance += amt; if (amt>100000) A->balance += A->bonus; } // How can I put savings and checking accounts into same array? // What would you call the TYPE of the array? ///////// int main(int argc, char** argv) { checking myaccount = newchecking(100,1); savings youraccount = newsavings(200,2); withdraw(myaccount,50); // not myaccount->withdraw(50); deposit(youraccount,100); account B[3]; B[0] = (account)myaccount; // just erased some type info B[1] = (account)youraccount; if (argc>1) B[2] = (account)newchecking(500,3); else B[2] = (account)newsavings(500,3); int i= 0; // withdraw $5 from every account for(;i<3;i++) withdraw(B[i],5); // which withdraw is being called? // ANSWER: the original one, because ALL THE TYPE INFO I HAVE ABOUT B[i] // is that it's "account" return 0; } /* How is this "inferior" to Java? Only real difference so far: everything is public (is your balance really secure?) Garbage collection,type safety are other comparisons to Java, but these issues are arguably orthogonal to oop. We're interested in OOP HERE! */