CS101: Fundamentals of Computer Programming Dr. Tejada stejada@usc.edu www-bcf.usc.edu/~stejada Week 8: Abstract Data Types
Object- Oriented Programming Model the applica6on/so9ware as a set of objects that interact with each other Objects fuse data (i.e. variables) and func6ons (a.k.a methods) that operate on that data into one item (i.e. object) Like structs but now with associated func6ons/methods Objects become the primary method of encapsula6on and abstrac6on Encapsula6on Hiding of data and implementa6on details (i.e. make so9ware modular) Only expose a well- defined interface to anyone wan6ng to use our object Abstrac6on How we decompose the problem and think about our design rather than the actual code
3 Classes Object- oriented design (OOD): a problem solving methodology Objects: components of a solu6on Class: a collec6on of a fixed number of components Member: a component of a class
4 Classes Class defini6on: Defines a data type; no memory is allocated Don't forget the semicolon a9er the closing brace Syntax:
5 Classes Class member can be a variable or a func6on If a member of a class is a variable It is declared like any other variable You cannot ini6alize a variable when you declare it If a member of a class is a func6on Func6on prototype is listed Func6on members can (directly) access any member of the class
6 Classes Three categories of class members: private (default) Member cannot be accessed outside the class public Member is accessible outside the class protected
7 Unified Modeling Language Class Diagrams Unified Modeling Language (UML) nota6on: used to graphically describe a class and its members +: member is public -: member is private #: member is protected
8 Unified Modeling Language
9 Variable (Object) Declara6on Once defined, you can declare variables of that class type clocktype myclock; clocktype yourclock; A class variable is called a class object or class instance
10 Accessing Class Members Once an object is declared, it can access the public members of the class Syntax: The dot (.) is the member access operator If an object is declared in the defini6on of a member func6on of the class, it can access the public and private members
11 Built- in Opera6ons on Classes Most of C++ s built- in opera6ons do not apply to classes Arithme6c operators cannot be used on class objects unless the operators are overloaded Cannot use rela6onal operators to compare two class objects for equality Built- in opera6ons that are valid for class objects: Member access (.) Assignment (=)
12 Assignment Operator and Classes
13 Class Scope A member of the class is local to the class Can access a class member outside the class by using the class object name and the member access operator (.)
14 Func6ons and Classes Objects can be passed as parameters to func6ons and returned as func6on values As parameters to func6ons Objects can be passed by value or by reference If an object is passed by value Contents of data members of the actual parameter are copied into the corresponding data members of the formal parameter
15 Implementa6on of Member Func6ons
16 Reference Parameters and Class Objects (Variables) Pass by reference is an efficient way to pass a variable as a parameter Problem: when passing by reference, the actual parameter changes when formal parameter changes Solu6on: use const in the formal parameter declara6on
17 Unified Modeling Language
18 Implementa6on of Member Func6ons myclock.equaltime(yourclock);
19 Implementa6on of Member Func6ons Once a class is properly defined and implemented, it can be used in a program A program that uses/manipulates objects of a class is called a client of that class When you declare objects of the class clocktype, each object has its own copy of the member variables (hr, min, and sec) Called instance variables of the class Every object has its own instance of the data
20 Accessor and Mutator Func6ons Accessor func6on: member func6on that only accesses the value(s) of member variable(s) Mutator func6on: member func6on that modifies the value(s) of member variable(s) Constant func6on: Member func6on that cannot modify member variables Use const in func6on heading
21 Order of public and private Members of a Class C++ has no fixed order in which to declare public and private members By default, all members of a class are private Use the member access specifier public to make a member available for public access
22 Constructors Use constructors to guarantee that member variables of a class are ini6alized Two types of constructors: With parameters Without parameters (default constructor) Name of a constructor = name of the class A constructor has no type
23 Constructors A class can have more than one constructor Each must have a different formal parameter list Constructors execute automa6cally when a class object enters its scope They cannot be called like other func6ons Which constructor executes depends on the types of values passed to the class object when the class object is declared
24 Constructors clocktype() { hr=0; min=0; sec=0; clocktype(int hour, int minutes, int seconds) { hr=hour; min=minutes; sec=seconds;
25 Invoking a Constructor A constructor is automa6cally executed when a class variable is declared Because a class may have more than one constructor, you can invoke a specific constructor
26 Invoking the Default Constructor To invoke the default constructor: Example: clocktype yourclock;
27 Invoking a Constructor with Parameters clocktype myclock(14,8,25); Number and type of arguments should match the formal parameters (in the order given) of one of the constructors Otherwise, C++ uses type conversion and looks for the best match Any ambiguity causes a compile- 6me error
28 Arrays of Class Objects (Variables) and Constructors If you declare an array of class objects, the class should have the default constructor
29 Classes and Constructors: A Precau6on If a class has no constructor(s), C++ provides the default constructor However, object declared is s6ll unini6alized If a class includes constructor(s) with parameter(s), but not the default constructor C++ does not provide the default constructor
30 Destructors Destructors are func6ons without any type The name of a destructor is the character '~' followed by class name For example: ~clocktype(); A class can have only one destructor The destructor has no parameters Destructor automa6cally executes when the class object goes out of scope
31 A struct Versus a class By default, members of a struct are public private specifier can be used in a struct to make a member private By default, the members of a class are private classes and structs have the same capabili6es
32 A struct Versus a class In C++, the defini6on of a struct was expanded to include member func6ons, constructors, and destructors If all member variables of a class are public and there are no member func6ons Use a struct
33 Classes and Abstract Data Types Abstrac6on Separa6ng design details from usage Separa6ng the logical proper6es from the implementa6on details Abstrac6on can also be applied to data Abstract data type (ADT): data type that separates the logical proper6es from the implementa6on details
34 Informa6on Hiding Information hiding: hiding the details of the operations on the data Interface (header) file: contains the specification details File extension is.h Implementation file: contains the implementation details File extension is.cpp In header file, include function prototypes and comments that briefly describe the functions Specify preconditions and/or postconditions
35 Informa6on Hiding Implementa6on file must include header file via include statement In include statement: User- defined header files are enclosed in double quotes System- provided header files are enclosed between angular brackets
36 Implementa6on of Member Func6ons Must write the code for func6ons defined as func6on prototypes Prototypes are le9 in the class to keep the class smaller and to hide the implementa6on To access iden6fiers local to the class, use the scope resolu6on operator ::
Example: Deck of cards Objects contain: Data members Data needed to model the object and track its state/ operation (just like structs) Methods/Functions Code that operates on the object, modifies it, etc. Deck Data members: Array of 52 entries (one for each card) indicating their ordering Top index Deck Methods/Functions Shuffle(), Cut(), Get_top_card()
UML (Unified Modeling Language) class name (e.g. Deck) Member functions + shuffle() : void + cut() : void + get_top_card() : int - cards[52] : int - top_index : int Member data class Deck { public: Deck(); // Constructor ~Deck(); // Destructor void shuffle(); void cut(); int get_top_card(); private: int cards[52]; int top_index; ;
C++ Classes Programming construct used to define objects, their data members, and methods/functions Similar idea to structs Steps: Define the class data members and method prototypes (usually in a separate header file) Write the methods in a separate.cpp file Instantiate/Declare object variables and use them by calling their methods Terminology: Class = Definition/Blueprint of an object Object = Instance of the class, actual allocation of memory, variable, etc. class Deck { public: Deck(); // Constructor ~Deck(); // Destructor void shuffle(); void cut(); int get_top_card(); private: int cards[52]; int top_index; ; #include<iostream> #include deck.h // Code for each prototyped method #include<iostream> #include deck.h int main() { Deck d; int hand[5]; d.shuffle(); d.cut(); for(int i=0; i < 5; i++){ hand[i] = d.get_top_card(); deck.h deck.cpp poker.cpp
Class Definition class name { ; Each function or data member can be classified as public, private, or protected Private: Can call or access only by methods/functions that are part of that class Public: Can call or access by any other code Protected: More on this later Everything private by default so you must use public: to make things visible Make the interface public and the guts/inner-workings private class Deck { public: Deck(); // Constructor ~Deck(); // Destructor void shuffle(); void cut(); int get_top_card(); private: int cards[52]; int top_index; ; #include<iostream> #include deck.h // Code for each prototyped method #include<iostream> #include deck.h int main() { Deck d; int hand[5]; d.shuffle(); d.cut(); d.cards[0] = ACE;//won t compile d.top_index = 5; //won t compile deck.h deck.cpp poker.cpp
Constructors / Destructors Constructor is a function of the same name as the class itself It is called automatically when the object is created Use to initialize your object to desired state Returns nothing Destructor is a function of the same name as class itself with a ~ in front Called automatically when object goes out of scope Use to delete any memory allocated by the object Returns nothing class Deck { public: Deck(); // Constructor ~Deck(); // Destructor... ; #include<iostream> #include deck.h Deck::Deck() { top_index = 0; for(int i=0; i < 52; i++){ cards[i] = i; Deck::~Deck() { #include<iostream> #include deck.h int main() { Deck d; // Deck() is called... return 1; // ~Deck() is called since // function is done deck.h deck.cpp poker.cpp
Writing Member Functions When writing member functions, we must scope our functions This allows the compiler to check access to private/public variables Without the scope operator [i.e. void shuffle() rather than void Deck::shuffle() ] the compiler would think that the function is some outside function (not a member of Deck) and thus generate an error when it tried to modify the cards array. class Deck { public: Deck(); // Constructor ~Deck(); // Destructor... ; #include<iostream> #include deck.h Deck::Deck() { top_index = 0; for(int i=0; i < 52; i++){ cards[i] = i; Deck::~Deck() { void Deck::shuffle() { cut(); //calls cut() for the object... int Deck::get_top_card() { top_index++; return cards[top_index-1]; deck.h deck.cpp
Calling Member Functions Member functions are called by preceding their name with the specific object that it should operate on d1 d1.shuffle() indicates the code of shuffle() should be operating implicitly on d1 s data member vs. d2 or any other Deck object d1 cards[52] top_index cards[52] d2 0 1 2 3 4 5 6 7 top_index #include<iostream> #include deck.h int main() { Deck d1, d2; int hand[5]; d1.shuffle(); // not Deck.shuffle() or // shuffle(d), etc. 0 for(int i=0; i < 5; i++){ hand[i] = d1.get_top_card(); cards[52] top_index 0 1 2 3 4 5 6 7 0 41 27 8 39 25 4 11 17 1
Calling Member Functions Within a member function we can just call other member functions directly. d1 s data will be modified (shuffled and cut) d1 is implicitly passed to shuffle() d1 cards[52] top_index 41 27 8 39 25 4 11 17 1 cards[52] d2 0 1 2 3 4 5 6 7 top_index 0 Since shuffle was implicitly working on d1 s data, d1 is again implicitly passed to cut() #include<iostream> #include deck.h int main(int argc, char *argv[]) { Deck d1, d2; int hand[5]; d1.shuffle();... #include<iostream> #include deck.h void Deck::shuffle() { cut(); // calls cut() // for this object for(i=0; i < 52; i++){ int r = rand() % (52-i); int temp = cards[r]; cards[r] = cards[i]; cards[i] = temp; void Deck::cut() { // swap 1 st half of deck w/ 2 nd poker.cpp deck.cpp
Class Pointers Can declare pointers to classes Use -> operator to access member functions or data d1 cards[52] top_index cards[52] d2 0 1 2 3 4 5 6 7 top_index #include<iostream> #include deck.h 0 1 2 3 4 5 6 7 0 0 int main() { Deck *d1; int hand[5]; d1 = new Deck(); d1->shuffle(); for(int i=0; i < 5; i++){ hand[i] = d1->get_top_card(); delete d1; d1 cards[52] top_index 41 27 8 39 25 4 11 17 1
Class Constructors / Destructors Constructor is a function of the same name as the class itself It is called automatically when the object is created (either when declared or when allocated via new ) Use to initialize your object to desired state Returns nothing Destructor is a function of the same name as class itself with a ~ in front Called automatically when object goes out of scope (i.e. when it is deallocated by delete or when scope completes) Use to delete any memory allocated by the object Returns nothing class Deck { public: Deck(); // Constructor ~Deck(); // Destructor... ; #include<iostream> #include deck.h Deck::Deck() { top_index = 0; for(int i=0; i < 52; i++){ cards[i] = i; Deck::~Deck() { #include<iostream> #include deck.h int main() { Deck *dptr; dptr = new Deck(); // Deck() is // called dptr->shuffle(); delete dptr; // ~Deck() is called deck.h deck.cpp poker.cpp
Example Student Class Recall unlike structs where other code can access member variables, other code (nonmember functions of the class) cannot access private class members directly class Student { public: Student(); // Constructor 1 Student(string name, int id, double gpa); // Constructor 2 ~Student(); // Destructor... private: string _name; int _id; double _gpa; ; student.h #include<iostream> #include <string> int main() { Student s1; string myname; cin >> myname; s1._name = myname; //compile error...
Accessor / Mutator Methods Define public get (accessor) and set (mutator) functions to let other code access desired private data members #include<iostream> #include <string> int main() { Student s1; string myname; cin >> myname; s1.set_name(myname); string another_name; another_name = s1.get_name();... class Student { public: Student(); // Constructor 1 Student(string name, int id, double gpa); // Constructor 2 ~Student(); // Destructor string get_name(); int get_id(); double get_gpa(); void set_name(string s); void set_id(int i); void set_gpa(double g); private: string _name; int _id; double _gpa; ; string Student::get_name() { return _name; int Student:: get_id() { return _id; void Student:: set_name(string s) { _name = s; void Student:: set_gpa(double g) { _gpa = g; student.h student.cpp
Multiple Constructors Can have multiple constructors with different argument lists #include<iostream> #include <string> int main() { Student s1; // calls Constructor 1 string myname; cin >> myname; s1.set_name(myname); s1.set_id(214952); s1.set_gpa(3.67); Student s2(myname, 32421, 4.0); // calls Constructor 2 class Student { public: Student(); // Constructor 1 Student(string name, int id, double gpa); // Constructor 2 ~Student(); // Destructor string get_name(); int get_id(); double get_gpa(); void set_name(string name); void set_id(int id); void set_gpa(double gpa); private: string _name; int _id; double _gpa; ; Student::Student() { _name =, _id = 0; _gpa = 2.0; Student::Student(string name, int id, double gpa) { _name = name; _id = id; _gpa = gpa; student.h student.cpp