A C++ Class contains:
A sample C++ class can be outlined as:
// An Example Class class AnExampleClass { // state definitions public: // interface declarations private: // implementation method declarations }; // member method implementation
Here is an example C++ class of a Bank Account class as shown in Figure 3.1, “A Sample Bank Account
Class”, with private
notated with "-" and public
notated with "+".
1 2 // Basic Bank Account Example 3 4 #include<iostream> 5 6 using namespace std; 7 8 class Account{ 9 10 private: 11 12 int accountNumber; 13 float balance; 14 15 public: 16 17 virtual void display(); 18 virtual void makeLodgement(float); 19 virtual void makeWithdrawal(float); 20 }; 21 22 void Account::display(){ 23 cout << "account number: " << accountNumber 24 << " has balance: " << balance << " Euro" << endl; 25 } 26 27 void Account::makeLodgement(float amount){ 28 balance = balance + amount; 29 } 30 31 void Account::makeWithdrawal(float amount){ 32 balance = balance - amount; 33 } 34 35 int main() 36 { 37 Account a; 38 a.display(); //will output rubbish for the states 39 } 40
The source code for this is in
BasicAccount.cpp
The Interface:
Provides a contract between the users of the class and the implementor.
The user of a class/object can only manipulate the states via the interface.
The user cannot modify the state directly.
The implementor undertakes to provide all the functionality of the interface.
If the interface must be changed then a new contract must be negotiated with the user. This will cause the user a lot of unnecessary work.
The code above shows how we can define and implement a class. If we wish to use this class, we can create an object of the class and manipulate it directly, for example:
int main() { Account myAccount; cout << "Account Details:"; myAccount.display(); myAccount.makeLodgement(2300.00); cout << "Account Details:"; myAccount.display(); myAccount.balance = 2300.00; // ERROR! cout << "Account Balance:" << myAccount.balance << endl; // ERROR! }
If you wish to assign a new object to an existing reference, even after initialisation use:
int main() { Account myAccount; // assigns an object to the reference myAccount = Account(); // allows the assignment of a new account object }
© 2006 Dr. Derek Molloy (DCU).