Introduction to Classes and Objects n Members Public

Introduction to Classes and Objects n Members: Public and Private n Enumerations - declared in classes n Constructors and Destructors n Member Functions and Data Members n const for functions and parameter modes n

Objects vs Variables n Similarities between Objects and Variables l l Both can be declared, initialized, used as an argument to an operator with the appropriate prototype (and be changed, if it is passed as a reference argument, to a state change operator) Differences between Objects and Variables s An object is constructed from a class in a library; a variable is declared from a type built-in to C++ An object typically stores more complicated state (multiple values); a variable stores simple state (one value) An object can be used in a special way to call member functions of its class; a variable cannot be used in this way 46 -699 2

Classes and Objects n Analogies l l n Class º Type (classes are programmer-defined types) Object º Variable (objects are variables with lots of state) Declarations of objects and variables are similar l Variables are declared from a type (in a declaration) s l Object construction syntax: class object(initial-values); Objects can be used to call member functions (which can return values or change an object’s state) s n Variable declaration syntax: type variable=initial-value; Objects are constructed from a class (in a declaration) s n 46 -699 3 Member function call syntax: object. function(arguments) Example: the Account class Account My. Account; //Construct an Account object My. Account. Balance. Inquiry(); //Returns the balance inquiry info

More on Classes n Class declarations specify both State (data) and Behavior l l l n Complexity is distributed among the classes that a program uses Programmers must understand the behavior (operators and functions) declared in a class to use such constructed objects in their programs; choose meaningful names for functions A class can be viewed as a library of functions that can be applied to objects constructed from that class Each class is separated into two related files l Declaration (. h): declares a class and its documentation s l To be read by any programmer who wants to use the class Definition (. cpp): defines member functions s n 46 -699 4 To be read only by the programmer maintaining the class Examples l Account. h and Account. cpp

Members of a Class n Members: the functions and data declared in a class l l n 46 -699 5 Member Functions: behaviors declared inside a class Data Members : data (state) declared inside a class Class declarations are divided into two parts l public : s s s l Declares members visible/usable in any code that #includes the class Most (but not all) member functions are declared to be public Class constructors and destructors are all public private/protected: s s s Declares members visible/usable only by the members of that class Any users of the class has no access to this info. In most classes, all data members are declared to be private protected members are declared in the context of class inheritance protected members are private to all outside members except for derived classes more on protected members later

Class Declarations n Simplified Syntax class-declaration Ü class identifier { public: {member-declaration} private: {member-declaration} }; member-declaration Ü constructor-declaration | function-declaration | declaration includes the declaration of variables and enumerations n Semantics l The identifier after class names a class that can be used anywhere that a built-in type can be used: to declare objects, and specify the return type and argument types in a function 46 -699 6

Accessing Class Members n To write code that constructs object from a class and uses objects to access public members in the class l n #include the header file of the class To use an object to call a member function of its class l object. function(arguments) s s n To use an object to access a data member of its class l object. data s s n Most member functions are public, so we can call them in our code All function calls include () - even when there are no arguments Most data members are private, so we can’t access them in our code example : My. Account. Balance = 100000; would be illegal Before examining classes in more detail, we need to learn a bit about enumeration types first 46 -699 7
![Declaring Enum(eration)s in a Class n Syntax enum-declaration Ü enum identifier {[enum-list]}; enum-list Ü Declaring Enum(eration)s in a Class n Syntax enum-declaration Ü enum identifier {[enum-list]}; enum-list Ü](http://slidetodoc.com/presentation_image_h2/1735d9e377108b4f117b3e88e82d08f5/image-8.jpg)
Declaring Enum(eration)s in a Class n Syntax enum-declaration Ü enum identifier {[enum-list]}; enum-list Ü enumerator{, enumerator} enumerator Ü identifier [= compile-time-expression]; compile-time-expression is any expression whose value can be computed at compile time (before a program runs); mostly these are literals or simple arithmetic operators applied to literals (i. e. , you cannot prompt the user for a compile-time value); these compile time expressions must be of type int n Examples enum Seed {randomized, standardized}; enum State {waiting, on. Board, served}; enum Direction {up, down, none}; 46 -699 8

Enumeration Semantics l l l The identifier after the word enum names a new type; this type can be used everywhere a built-in type can be used Each enumerator identifier specified inside the braces after the new type name becomes a literal value of that type These literals are interconvertable with the type int s s s n 46 -699 9 If a literal is followed by = compile-time-expression then it interconverts with the value of the compile time expression Otherwise, if it is the first literal in the braces, its value is 0; if it follows another literal, its value is one greater than the value of the literal it follows (these rules apply to most enumeration declarations) In the enumeration type State waiting « 0, on. Board « 1, served « 2 cout Semantics of enumeration literals l l enumeration literals inserted onto an output stream display according to their equivalent int value eg: state my. State = waiting; cout<<my. State;

Referring to class-declared enums n Inside a class declaration, its enum literals are referred to just by their enumerator-identifier (e. g. , Off, Forward) void Move (State my. State = on. Board, Direction elevator. Direction = up); n 46 -699 10 When referring to class-declared enums in a program that #includes that class, we must use the fully qualified name of the enum literal (identifier is the class name) l l class-name: : enumerator-identifier eg: class Elevator{ enum direction {up, down, none} …. . } class Passenger{ public: Elevator: : direction my. Direction=Elevator: : up; …. . }

Enumeration Pragmatics n A class declares enumerations mostly for use as parameters/arguments to the constructors and member functions that it declares l l n The enumeration’s name is used as a parameter type in the declaration of constructors/member functions The enumeration’s literals are used as arguments to this parameter in object declarations or member function calls Enums are a simple data type whose use can clarify programs tremendously l Good enumeration names clarify constructors/member and function calls; compare s s Timer Answer_Time(Timer: : Off, Timer: : On); //Enums used Timer Answer_Time(1, 0); //Not used 46 -699 11

Class Constructors n 46 -699 12 Constructors are special members of a class l Constructors look like functions but specify no return type s s Not even a void return type, but literally no return type eg : Elevator(int ID, int floor. Num) Most constructors appear in the public part of a class declaration l C++ uses constructors to construct objects in declarations l The name of a constructor must be the same name as its class l Like functions, constructors can have parameters l s s The arguments matching these parameters, in an object declaration, are used to initialize the state of the object being constructed Constructors can be overloaded (most classes do overload constructors) —A class may declare many constructors, differentiated by their prototypes (the number and type of parameters: note default values) s s Constructors can have default arguments in case no programmer supplied arguments eg: Elevator(int id, int floor=0); Think of a class as a mold, and a constructor as a manufacturing device that produces a real object from the mold

Class Constructors (continued) n The arguments supplied to a constructor are used by the constructor to initialize the object l l n 46 -699 13 Private data members of the object typically store these values Other data members may be set to default values Declaring objects with class constructors looks similar to declaring variables of C++ built-in types using the parenthesized form of initialization l l int X = 3; has the same meaning as int X(3); Classs Constructors often need multiple arguments, which is easily done with the parenthesized form of initialization, enclosing all the initializing arguments in parentheses and separating them by commas (so the parentheses form is mandated here) s s Rational R 1(1, 2); Timer T(Timer: : CPU, Timer: : On, Timer: : Forward);

Constructor Examples n 46 -699 14 Some Constructor Declarations Account(); // initializes to default values Account (long Account. Number, double Balance = 100); Account(short pin, long Account. Number, double balance=100) Elevator (int floor. Num=1, Direction Direct=up); // default constructor (only one per class) Constructors often contain default arguments for some or all of their parameters last (few) parameters. This mechanism simplifies the construction of “typical” objects, but ultimately allows the programmer complete control over object initialization.

Object Constructions n 46 -699 15 Object Declarations (note the use of default arguments) Account My. Account; // uses default constructor Account My. Account(982626, 876. 23); // uses constructor 1 Account My. Account(6754, 982626, 890. 98); // uses constr 2 Elevator South. Elevator(5, Elevator: : down) Timer Speed_Test(Timer: : CPU); //Timer measures CPU time: it starts Off and runs Forward Timer Speed_Test(Timer: : Wall, Timer: : On); //Timer measures Wall time: it starts On and runs Forward

Classes and Objects n n 46 -699 16 A class is an object template; we can use the same class to construct many similar objects in a program, and then use the objects together. However the each object has its own identity and shares the same behavior space. Each object stores its own state (in its data members) Objects can only access its public members A common problem among novice programmers is to confuse an object with its class (or a variable with its type); this is especially true in programs that construct only one object from a class l l This leads to illegal function calls like Elevator. Move. To. Next. Floor() The name of an object (not a class) must appear before the.

Categories of Constructors n 46 -699 17 A default constructor can be used with no arguments: it either has no parameters, or every parameter has a default argument. For example Account (); Account (int pin = 1234, long Account. Num=366363, double balance=109. 09); l Correct way to use a default constructor to declare an object s Account My. Account; Elevator Any. Elevator; s Elevator Any. Elevator(); s l n Incorrect way to use a default constructor to declare an object //compile error A copy constructor has one parameter; its class is the same class as the new object that it constructs Account(const Account& X) l C++ uses a copy constructor to copy an object when it passes it by copy/value, as an argument to a function. l We can use it in a declaration to construct a copy of an object

Categories of Constructors (continued) n 46 -699 18 A convertor constructor can be used with one argument: it either has one parameter, or all parameters after the first must have default arguments). C++ can use a convertor constructor to automatically convert a value from the type/class of the argument into a value of the class -unless the word explicit appears before the constructor’s declaration, disallowing such conversions Rational (int Numerator, int Denominator = 1); explicit Modular_Counter (int Modulus, int Initially = 0); l Rational R 1; in 1+R 1 C++ uses the convertor constructor to automatically convert 1 to the Rational (1/1) so it can apply the operator+ declared with the Rational class l Using explicit in the Modular_Counter constructor disallows this automatic conversion - otherwise Modular_Counter M; in M = 1 C++ would convert 1 into a modular number with modulus 1 and value 0 (which would store 0 to M; we probably wanted to store the value 1 into M using some modulus)

Destructors n A special member of the class l n n n n 46 -699 19 ~Elevator() ; Destructor is the complement of the constructor Class destructor is called implicitly when the object is destroyed Only one destructor per class (no overloading) Receives no arguments Useful for dynamically allocated memory Object destructors are called when the object leaves its scope - end of object’s life Eg: void main() { {Elevator this. Elevator; …… } // this. Elevator leaves scope calls the destructor

About Member Functions n 46 -699 20 Calling a member function on an object. function(arguments) l C++ applies the member function to object, uses its arguments l Think of the object as an implicit argument to the member function: the member function can examine/change the state of the object used to call it l Examples: Elevator. move. To. Next. Floor(); int balance = my. Account. Balance(); my. Account. deposit(134. 56); cout << my. Account. balance() << endl; l

const/non-const Member Functions n If a member function declaration ends in const; it means that during the application of that function, the object’s data members cannot change; such a function is generically called an accessor: it can only accesses the object’s data members; it cannot change them l n n 46 -699 21 eg: double balance() const; If a member function declaration does not end in const; it means that during the application of that function the object’s data member can change (and most often do change); such a function is generically called a mutator: it can access and mutate (change) the object’s data members Identify accessor/mutator functions in class header files provided (see link demos)

Parameter Modes: copy/reference/const n A copy/value parameter (specified by just a type name) receives copy of the value of its matching argument: the argument can be any expression. l n Passing an argument to a parameter by copy/value is fast for built-in types, but can be slow for classes with lots of state A reference parameter (specified by a type name followed by &) refers to (or aliases) its matching argument: the argument must be a variable (of a built in type) or it can be a variable or a value of a class. It may change during the function call l l 46 -699 22 Passing an argument to a parameter by reference is fast When a reference parameter is modified in a function, its calling argument(actual parameter) changes.

Parameters (continued) n A const reference parameterl l n 46 -699 23 const reference parameter has the speed of a reference parameter and the security of a value parameter eg: void Account: : find. Average(const double b[]) Summary: Maximizing Safety & Speed l l l Built-in types: pass by copy/value, unless the argument can change Classes: pass by const reference, unless the argument can change eg: void IRSManager(const Account &E) s here IRSManager function can access your account , but not change its state.

More on Data Members n n Each Object store their state in their data members In most classes, data members are declared private l l n 46 -699 24 So, we cannot directly examine or change the data members in objects of that class; the state is private to the object But, we can call accessor member functions to examine an object’s data members and we can call mutator member functions to change the values of an object’s data members Private data members can be examined and changed only in a tightly controlled way: by calling member functions l l Accessors just return the value of the data member (e. g. , double show. Balance() const) Mutators act as safe interfaces for changing data members s s They can ensure the programmer doesn’t change the values of data members to something illegal; they can check for consistency with the other data members already stored in the object. Eg: void deposit(double Amount);

Semantic Comments for Classes n Besides pre-/postconditions for member functions, classes can also include semantic comments that state invariants for their data members. An invariant is l l True after each object of that class has been constructed True after each member function call s l n Remember that only member functions can alter the state (private data members) of objects, so they must preserve invariants So, it can be assumed true before each member function call Example (from Rational) // // Class Invariants: my_Numerator is positive or negative my_Denominator is always positive The fraction is always stored in lowest common terms: e. g. , my_Numerator has no factors in common with my_Denominator The value 0 is always represented as 0/1 46 -699 25

Using Constructors as Expressions n We mostly use constructors to instantiate objects l n 46 -699 26 The arguments to the constructor specify the initial values for the object’s data members We can use constructors to specify a value of the class l It is an anonymous variable (a variable without a name) that is discarded after the expression it is used in is evaluated n To compute 1+1/2+1/3 exactly we can write n or we can use two constructors as expressions Rational Temp 1(1), Temp 2(1, 2), Temp 3(1, 3); Rational R = Temp 1 + Temp 2 + Temp 3; Rational R = 1 + Rational(1, 2) + Rational(1, 3); l Here, Rational(1, 2) and Rational(1, 3) are anonymous variables representing the values 1/2 and 1/3 l So, 1 is automatically converted to Rational by a convertor constructor; then operator+ has two arguments that are both of class Rational, which matches the operator+ declared in rational. h; the result, a Rational, is added again with the same operator+ using Rational(1, 3) as its other argument

Operator Overloading for Classes n n 46 -699 27 A new class definition may require us to overload C++ operators for that class. Eg: matrix multiplication These overloaded operators are not declared in the class itself, but at the end of the. h file that declares the class l We overload << for outputting a value of the new class ostream& operator<<(ostream& OS, const Matrix& A); if we declare Matrix A(3, 4); then we can write cout << A; s l If the class describes a numeric type (as does Rational), we also might overload various arithmetic and relational operators s s Matrix operator+ (const Matrix& Left, const Matrix& Right); bool operator< (const Matrix& Left, const Matrix& Right); if we declare Matrix A(2, 3), B(2, 3), C(2, 3); then we can write C = A + B and if (A < B) … l l Note the use of const reference parameters for speed and safety We will discuss the syntax in operator overloading in lecture 3

Objects/Classes simplify Complexity n Our ability to write interesting programs is limited mostly by the complexity of the programs themselves l n n 46 -699 28 What information we need to remember (and what we can forget) about our programs when we create, debug, and enhance (maintain) them Most program composition methods are based on a divide and conquer approach l Divide one large problem into independent sub problems l We divide a program into the classes that it needs Classes allow us distribute complexity in this way s s l We focus on knowing the declaration of a class Once a class is working correctly, we can ignore details about how a class is implemented (these details are present in the. cpp file of the class); if someone else writes a class, we may never need to know its details When we write programs using objects/classes, each object/class captures some aspect of the program, and hides its complexity so that we are not overburdened with details

Explore and Experiment n 46 -699 29 Examine the demand. h, order. h, stock. h, and timer. h, rational. h files in the demo folder l l l Examine the enumeration types that they declare Examine the constructors that they declare Examine the member functions that they declare s l Examine the const and non-const member functions s l Remember the first are accessors and the second are mutators Examine the parameters to all the member functions s l Read about their details in the Semantic comments Identify copy/value, reference, and const reference parameter modes Note the private data members that they declare (try to understand why these data members are needed to store the state of an object, but don’t worry about them)

Drivers for Classes n 46 -699 30 A driver is a program that is associated with some class. It presents a menu to the user; by selecting from this menu, the user can individually execute each (or most) of the member functions declared in the class -to test drive them. Before executing a member function, the driver prompts the user for the argument(s) to pass to the function (if necessary). Some drivers include speed tests, timing some functions

Classes: Where are we heading? n n First learn to read and use classes Next learn to modify classes and write your own classes l n If you want, take a peek at the function definitions in the elevator. cpp and passenger. cpp files matching the corresponding. h files Finally, we will learn how to use inheritance to derive new classes from old ones (a very fast and powerful way to create new classes that are variations of base classes) Together, these three activities form the basis of “objectoriented programming” n 46 -699 31 Special Thanks to Rich Pattis for his enormous influence on this lecture
- Slides: 31