object-oriented programming in c++ lecture 2 classes and objects
TRANSCRIPT
Object-Oriented Programming in C++
Lecture 2
Classes and Objects
IntroductionLast lecture we•introduced the module•introduced C++This lecture we will•review the concept of classes and objects•discuss their representation using UML class diagrams•implement and use a simple C++ class•introduce C++ structures and enumeration types
Classes and objects
• a class is a programmer-created data type• it can have member variables (attributes)
– to hold data
• and member functions (methods)– to manipulate that data
• an object is an instance of a class– with specific values for the member variables
• normally the member variables are private– hidden within the object
• we interact with the object via its public methods• encapsulation
Example – Account class• consider a class to represent a bank account• what data do we need to store about a bank
account?– account balance– interest rate
• what functions are needed to manipulate this data?– get the balance, deposit money, withdraw money,
calculate and add the interest– create an account with a given initial balance and
interest rate• each bank account object will have its own
balance– and interest rate in this example
UML class diagrams
• UML (the Unified Modelling language) defines 13 standard diagrams for system modelling
• the class diagram is a useful way to represent a class– its member variables and methods– their type and visibility
• UML diagrams can have different levels of detail– from initial ideas (analysis) to implementation-
level documentation
UML diagram of an Account
Account
balanceinterest rate
create accountget balancedeposit moneywithdraw moneyadd interest
• the diagram has 3 sections• the class name is at the top • the variables are in the
middle• the functions are at the
bottom• this is an analysis-level
diagram• what should the
implementation-level diagram look like?
Implementation-level diagram of an Account
Account
-balance: double-interestRate: double
+Account(initalBalance: double, rate: double)+getBalance() : double+deposit(amount: double)+withdraw(amount: double)+addInterest()
• the member visibility is shown by:- private
+ public
# protected
• the type of each member is shown after the member name
C++ implementation of the Account class
class Account {private: // optional because members are private by default double balance; // amount of money held by this account double interestRate; // a monthly or yearly interest ratepublic: // create an account with an initial amount and a specified interest rate Account(double initialBalance, double rate) : balance(initialBalance), interestRate(rate){ }
// return the account's balance double getBalance(){ return balance;}
// add money to the account void deposit(double amount) { balance += amount;
} // continued on next slide
C++ implementation of the Account class
void withdraw(double amount) {// implement this method yourself}
// add money according to the interest rate.void addInterest() {
balance *= (1 + interestRate/100.0);// this is the same as balance = balance * (1 +
(interestRate/100) ); }
};
Using the Account class
• create a project
• put the Account class code into a header file called account.h– this is the account class definition
• create a source file called bank.cpp– this will contain the main method– which will create and test an Account object
bank.cpp#include <iostream>#include "account.h" using namespace std;void main(void){ Account stdAccount(100, 4); // create an account with £100and 4% interest rate stdAccount.addInterest(); cout << "Balance: " << stdAccount.getBalance()<< endl; stdAccount.deposit(50); cout << "Balance: " << stdAccount.getBalance()<< endl; stdAccount.withdraw(100); cout << "Balance: " << stdAccount.getBalance()<< endl; }
#include directives
#include <iostream>#include "account.h" •iostream is a library file
– the angled brackets indicate the file is in the C++ library directory
– path should already been set up in IDE•account.h was written by the programmer•the quotes indicate the file path and name•in this case, it is in the same directory as bank.cpp
Constructors
• the constructor is called when an object is first created– sets up the object in memory– with space for the member variables
• if the class does not have a constructor, a default no-argument constructor is used
• a constructor must have the same name as the class– and no return value
Account constructor• the constructor initialises the member variables balance and interestRate
Account(double initialBalance, double rate) : balance(initialBalance),interestRate(rate) { }
• this is equivalent to the Java-like constructorAccount(double initialBalance, double rate) { balance = initialBalance; interestRate = rate;}
• the first version initialises the member variables as they are created
• the second creates the member variables – then assigns them values within the constructor body– less efficient
Destructors
• a destructor is called when the object is destroyed– goes out of scope or is deleted
• a destructor has the same name as the class, preceded by a ~– it cannot have any parameters or return value– it is called automatically – never call it yourself– a destructor for the Account class: ~Account() { cout << "Closing the account. Final balance: " << balance << endl;
}
C++ structures
• C++ structures are similar to classes– they can have member variables and functions– however all members are public by default
• no encapsulation– an Account struct could have its balance changed
directly– rather through the deposit and withdraw
methods
• structs are useful to group together related data
Example structuresstruct Point3D {
float x;float y;float z;
};
int main() {Point3D A = { 10, 5.3, 6};Point3D B;B.x = 2.1;B.y = 2.4;B.z = 7.3;//....
}
Enumeration types• another useful programmer-defined type is the
enumeration• defines all possible values of a given typeenum colour { RED,ORANGE,YELLOW,GREEN,BLUE,VIOLET};int main() { colour hatColour = ORANGE;colour shirtColour = VIOLET;// ....
}• each enum value maps to an integer• RED is 0, ORANGE is 1….• less error-prone than using strings or constants
Summary
In this lecture we have•reviewed the concept of classes•discussed their representation using UML class diagrams•implemented and used a simple C++ class•introduced C++ structures and enumeration types
In the tutorial we will•implement the Account class•add more functionality and a menu-driven interface
Further reading
• Object Management Group – UML Resource Page http://www.uml.org/
• MSDN library – C++ language reference– Classes, structures and unions
http://msdn.microsoft.com/en-us/library/4a1hcx0y.aspx