Classes
Object-Oriented Design Method for designing computer programs Consider “objects” interacting in the program –Example: a zoo, a gradebook
OOD Goals Robustness –Gracefully handle failures Adaptability –Evolve as necessary Reusability –Many programs use same piece of code
OOD Principles Abstraction –Abstract Data Types (ADTs) –Interfaces Encapsulation –Information Hiding Modularity –Easily plug together components
What is a class? Data and the functions (methods) that operate on that data – collectively called members –Example: bank account class Provide structure for organizing programs –Almost like an advanced struct
Syntax class classname { private: … public: … } private only accessible within the class public accessible from anywhere (like with a struct)
Member Functions Typically, data (variables) declared private Functions operate on data –accessor functions – read data, provide access to data but do not change it –update functions – change data examples from bank account, zoo??? –constructor – builds a new object
Writing Classes Typically, two files header and source Header declares member variables, provides function prototypes and bodies of short functions Source provides code for rest of functions Allows separation of interface and implementation Reduces compile time
Bank Account Interface BankAccount(double initial_balance); void withdraw(double amount); void deposit(double amount); double checkBalance() const;
Creating and Using Objects BankAccount b(500); //Type Name(constructor parameters); //how would you withdraw funds?
Creating and Using Objects BankAccount b(500); Type Name(constructor parameters); //how would you withdraw funds? b.withdraw(300); object_name.method_name(param list);
Constructor BankAccount::BankAccount(double init_balance) class_name(parameter list) Special-case function called when a new object is created Used to initialize member variables –Examples? Default constructor takes no parameters
Alternative Initialization BankAccount::BankAccount(double init_balance) { balance = init_balance; } BankAccount::BankAccount(double init_balance=0) : balance(init_balance) { }
Destructor BankAccount::~BankAccount() ~class_name Used if class allocates memory dynamically (uses new) Delete all dynamically declared objects
const const member function will not change any class variables double checkBalance() const {…}
friend Allow a class to access the private members of another class Operator overloading Closely related classes
static Static class member - a global variable with scope the same as a class member –1 per class, not per object Example - car serial number
More Examples An appointment book/calendar A tic tac toe game Airline example