CSE 143 ADTs: Great Idea, but... • How do we actually get modularity, abstraction, ADTs, black boxes, etc. in our Classes programs? • How do we actually encapsulate? • Main programming construct: the class [Chapter 3, pp. 125-131] • Based on C struct. • C structs contain only data • C++ classes can also contain operations (functions) 4/4/2001 4/4/2001 E-1 E-2 A Bank Account Class (I) A Class is a Type // Representation of a bank account BankAccount a1 , a2 ; class BankAccount { public: • The code above creates two instances of the // set account owner to given name void init(string name); BankAccount class. • Each instance has its own copy of the data // add amount to account balance void deposit(double amount); members of the class: // get current account balance double amount(); owner: “Jack” owner: “Jill” balance: 200.17 balance: 940.15 string owner; //account holder’s name double balance; //current account balance a2 a1 }; 4/4/2001 4/4/2001 E-3 E-4 How Do You Access It? How Clients Use a Class • A class is treated like any programmer-defined BankAccount a1, a2; type. For example, you can: • Declare variables of that type: owner: “Jack” owner: “Jill” balance: 200.17 balance: 940.15 BankAccount anAccount; a1 a2 • Can have arguments (parameters) of that type: void doSomething (BankAccount anotherAccount); • Access data members just like a struct • Use one type to build other types: if (a1.balance == 200.17) … // is True class Bank { a2 = a1; // allowed public: . . . • Access member functions ("methods") that way too: private: BankAccount accounts[100]; a1.deposit(12.75); // TA payday! }; 4/4/2001 4/4/2001 E-5 E-6 CSE 143 E
A Bank Account Class (II) Methods • The class's operations are implemented with // Representation of a bank account class BankAccount { functions: "methods" public: • To call a method (member function), specify an // set account owner to given name void init(string name); object (class instance), select the function // add amount to account balance member with a ‘ . ’, and append a parameter list void deposit(double amount); // get current account balance BankAccount anAccount; double amount(); private: anAccount.init(“Fred Flinstone”); string owner; // account holder’s name double balance; // current account balance }; Object Member Parameter(s) • Some members are public, some are private function 4/4/2001 4/4/2001 E-7 E-8 Public vs. Private Operations on instances • Private members are hidden from clients . • Most built-in C++ operators DO NOT apply to • The compiler will not allow client code to access them. class instances • You cannot (for example): • There's a "wall" around them • Public members may be used directly by clients • use the “+” to add two BankAccount instances • use the “==“ to compare to accounts for equality • Windows or holes through the wall • The BankAccount implementation can see both • To the client, the only valid operations on instances are • Trivia: “private” is the default for classes • assignment (“=“) • F or the BankAccount class, • member selection (“.”) • How many data members? private? public? • plus, can use any operations defined in the public • How many “methods”? interface of the class. • What can the client use directly? 4/4/2001 4/4/2001 E-9 E-10 Terminology Information Hiding • Think of a class as a cookie cutter, used to stamp • The private access modifier supports and out concrete objects (instances) enforces information hiding • Another view: objects as simple creatures that we // A client program . . . communicate with via “messages.” (function calls) BankAccount account; instance BankAccount myAccount; account.balance = 10000.0; // NO! why? argument cout << account.balance; // NO! why? myAccount.deposit(300.15); account.init(“Jill”); // ok? account.deposit(40.0); // ok? cout << account.amount(); // ok? message receiver cout << account.amount; // ???? selection cout << account; // ???? 4/4/2001 4/4/2001 E-11 E-12 CSE 143 E
Class Packaging Interface as Contract • C++ allows many legal ways to "package" classes. In The public parts of a class declaration define the interface that clients can use. CSE143 we generally follow this pattern: • For each class named X, a pair of files: X.cpp and X.h Module interface acts as a contract between client and implementer • X.h (specification file) • Client depends on interface not changing the declaration of only one class X maybe some constants • Doesn’t need to know any details of how module • X.cpp (implementation file) works, just what it does #include “X.h” • Implementer can change anything not in the interface, contains all the member function definitions and any other functions needed to implement them (e.g. to improve performance) • Client programs have #include “X.h” • Implementation is a “black box” ( encapsulation ), • Sometimes very closely related classes are packaged providing information hiding together 4/4/2001 4/4/2001 E-13 E-14 Class Declaration: Interface Building the Class: Implementation (Code) #ifndef BANKACCOUNT_H #include “BankAccount.h” Multiple inclusion hack – more below #define BANKACCOUNT_H // set account owner to given name void BankAccount::init(string name) { // Representation of a bank account class BankAccount { balance = 0.0; public: scope resolution operator owner = name; // set account owner to given name } void init(string name); need class name here // add amount to account balance // = current account balance void deposit(double amount); double BankAccount::amount() { // = current account balance return balance; but not here double amount(); private: } string owner; // account holder’s name // add amount to account balance double balance; // current account balance void BankAccount::deposit(double amount) { }; balance = balance + amount; #endif } BankAccount.h BankAccount.cpp 4/4/2001 4/4/2001 E-15 E-16 Declaration vs Definition Implementing Member Functions • In C++ (and C) there is a careful distinction • Implementations of member functions use between declaring and defining an item. classname :: prefix • Declaration: A specification that gives the • indicate which class the member belongs to • “ :: ” is called the scope resolution operator information needed to use an item • Within member function body: • function prototype • Refer to members directly • class declaration (specification in header file) • Can access any member, whether public or private! • Definition: The C++ construct that actually • Don’t reuse class member names for formal parameters creates/implements the item. and local variables (bad style) • full function w/body 4/4/2001 4/4/2001 E-17 E-18 CSE 143 E
One-Definition Rule (ODR) Multiple Inclusion • An item (class, function, etc.) may be declared Although an item may be declared in many different compilation units, it is a compile-time error as many times as needed in a program (i.e., if identifiers (function names, constants, etc.) are the same declaration may be #included in declared multiple times in one compilation unit: many files), but… ... const int MINSIZE = 20; • An item must be defined (actually created or void writeLetters (string word); ... implemented) exactly once in a program. #include "letters.h" letters.h ... word.h #include "letters.h" #include "word.h" ... main.cpp 4/4/2001 4/4/2001 E-19 E-20 Multiple Inclusion Hack Classes in the Big Picture • To avoid this problem, use preprocessor directives: correct Users wants efficient // letters.h easy to use reliable #ifndef LETTERS_H Preprocessor cheap #define LETTERS_H on-time directives ... improvable const int MINSIZE = 20; Engineering void writeLetters (string word); ... #endif abstraction testing, style, • Read the above as: code reuse verification standards “If the symbol LETTERS_H has not been defined, compile the code modular design through #endif (and define LETTERS_H ), otherwise skip that code” • Effect: the header is only processed the first time it encountered (#included) when compiling a particular C++ support classes source file 4/4/2001 4/4/2001 E-21 E-22 Summary • class construct for Abstract Data Types • Function members (operations) • Data members (representation) • public vs. private members • Specification vs Implementation • Related concept: Declaration vs Definition • Implementation signaled by classname:: • Implementations can access all members, public or private • Clients can only access public members • Clients generally have multiple instances of a few classes 4/4/2001 E-23 CSE 143 E
Recommend
More recommend