CS 144 Advanced C++ Programming February 21 Class Meeting

Slides:



Advertisements
Similar presentations
Classes & Objects INTRODUCTION : This chapter introduces classes ; explains data hiding, abstraction & encapsulation and shows how a class implements these.
Advertisements

Chapter 8 Scope, Lifetime and More on Functions. Definitions Scope –The region of program code where it is legal to reference (use) an identifier Three.
Classes & Objects classes member data and member function access control and data hiding instantiation of objects class constructor and destructor objects.
1 Chapter 11 Structured Types, Data Abstraction and Classes Dale/Weems/Headington.
Computer Science 1620 Function Scope & Global Variables.
1 Lecture 29 Chapter 11 Structured Types, Data Abstraction and Classes Dale/Weems/Headington.
Engineering Problem Solving With C++ An Object Based Approach Chapter 8 Introduction to Classes.
Chapter Objectives You should be able to describe: Object-Based Programming Classes Constructors Examples Common Programming Errors.
Object Oriented Programming C++. ADT vs. Class ADT: a model of data AND its related functions C++ Class: a syntactical & programmatic element for describing.
Object Oriented Programming C++. ADT vs. Class ADT: a model of data AND its related functions C++ Class: a syntactical & programmatic element for describing.
Classes in C++ Bryce Boe 2012/08/15 CS32, Summer 2012 B.
Review of C++ Programming Part II Sheng-Fang Huang.
Chapter 10 Defining Classes. User-defined Types Are data types defined by programmers. Include: – typedef: simple data definition – struct: a structure.
ADTs and C++ Classes Classes and Members Constructors The header file and the implementation file Classes and Parameters Operator Overloading.
Chapter 10 Introduction to Classes
Classes Representing Non-Trivial Objects. Problem Write a program that reads a temperature (either Fahrenheit or Celsius), and displays that same temperature.
C++ Programming Lecture 11 Functions – Part III By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department.
Chapter 3 Part I. 3.1 Introduction Programs written in C ◦ All statements were located in function main Programs written in C++ ◦ Programs will consist.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Lucas Bang Lecture 16: Introduction to C++
OOP in C++ CS 124. Program Structure C++ Program: collection of files Source (.cpp) files be compiled separately to be linked into an executable Files.
2 Objectives You should be able to describe: Object-Based Programming Classes Constructors Examples Common Programming Errors.
CS Introduction to Data Structures Spring Term 2004 Franz Hiergeist.
Chapter 11 Friends and Overloaded Operators. Introduction to function equal // Date.h #ifndef _DATE_H_ #define _DATE_H_ class CDate { public: CDate();
1 More Operator Overloading Chapter Objectives You will be able to: Define and use an overloaded operator to output objects of your own classes.
By Joaquin Vila Prepared by Sally Scott ACS 168 Problem Solving Using the Computer Week 13 More on Classes Chapter 8 Week 13 More on Classes Chapter 8.
Structures Revisited what is an aggregate construct? What aggregate constructs have we studied? what is a structure? what is the keyword to define a structure?
Friend Functions.  An ordinary function that is given special access to the private members of a class  NOT a member function of the class  Prototype.
1 Classes II Chapter 7 2 Introduction Continued study of –classes –data abstraction Prepare for operator overloading in next chapter Work with strings.
Department of Computer Science and Engineering, HKUST 1 HKUST Summer Programming Course 2008 Using Member Functions and Data Members.
CSE 332: C++ template examples Today: Using Class and Function Templates Two examples –Function template for printing different types –Class template for.
Operator Overloading Chapter Objectives You will be able to Add overloaded operators, such as +,-, *, and / to your classes. Understand and use.
1 Data Structures CSCI 132, Spring 2014 Lecture 2 Classes and Abstract Data Types Read Ch Read Style Guide (see course webpage)
1 C++ Classes & Object Oriented Programming Overview & Terminology.
1 Chapter 12 Classes and Abstraction. 2 Chapter 12 Topics Meaning of an Abstract Data Type Declaring and Using a class Data Type Using Separate Specification.
Chapter 12 Classes and Abstraction
C++ Lesson 1.
Introduction to C++ (Extensions to C)
Submission Example May 14, 2018
CMPE Data Structures and Algorithms in C++ September 21 Class Meeting
Structures Revisited what is an aggregate construct? What aggregate constructs have we studied? what is a structure? what is the keyword to define a structure?
Overloading Operator MySting Example
CMPE 135: Object-Oriented Analysis and Design September 14 Class Meeting Department of Computer Engineering San Jose State University Fall 2017 Instructor:
Andy Wang Object Oriented Programming in C++ COP 3330
CMPE Data Structures and Algorithms in C++ September 28 Class Meeting
Structures Revisited what is an aggregate construct? What aggregate constructs have we studied? what is a structure? what is the keyword to define a structure?
Chapter Structured Types, Data Abstraction and Classes
CMPE 135: Object-Oriented Analysis and Design October 17 Class Meeting
CMPE 135: Object-Oriented Analysis and Design October 17 Class Meeting
CMPE Data Structures and Algorithms in C++ February 22 Class Meeting
CMPE 180A Data Structures and Algorithms in C++ February 1 Class Meeting Department of Computer Engineering San Jose State University Spring 2018 Instructor:
Chapter 11 - Templates Outline Introduction Function Templates Overloading Function Templates Class Templates Class.
Learning Objectives Classes Constructors Principles of OOP
Classes Short Review of Topics already covered Constructor
Classes.
Namespaces How Shall I Name Thee?.
Chapter 11 - Templates Outline Introduction Function Templates Overloading Function Templates Class Templates Class.
COP 3330 Object-oriented Programming in C++
Chapter 11 - Templates Outline Introduction Function Templates Overloading Function Templates Class Templates Class.
Functions Imran Rashid CTO at ManiWeber Technologies.
CS 144 Advanced C++ Programming January 31 Class Meeting
CS 144 Advanced C++ Programming February 12 Class Meeting
Class: Special Topics Overloading (methods) Copy Constructors
Class rational part2.
CS 144 Advanced C++ Programming March 21 Class Meeting
Chapter 11 - Templates Outline Introduction Function Templates Overloading Function Templates Class Templates Class.
CS 144 Advanced C++ Programming April 30 Class Meeting
CS 144 Advanced C++ Programming April 30 Class Meeting
四時讀書樂 (春) ~ 翁森 山光照檻水繞廊,舞雩歸詠春風香。 好鳥枝頭亦朋友,落花水面皆文章。 蹉跎莫遣韶光老,人生唯有讀書好。
Object Oriented Programming
Introduction to Classes and Objects
Presentation transcript:

CS 144 Advanced C++ Programming February 21 Class Meeting Department of Computer Engineering San Jose State University Spring 2019 Instructor: Ron Mak www.cs.sjsu.edu/~mak

Abstract Data Types A data type specifies: what values are allowed what operations are allowed An abstract data type (ADT): allows its values and operations to be used hides how the values and operations are implemented Example: The predefined type int is an ADT. You can use integers and the operators + - * / % But you don’t know how they’re implemented.

Abstract Data Types, cont’d To make your class an ADT, you must separate: The specification of how a type is used. The details of how the type is implemented. To ensure this separation: Make all member variables private. Make public all the member functions that a programmer needs to use, and fully specify how to use each one. Make private all helper member functions. Is the Birthday class an ADT?

Public vs. Private Public member variables and functions of a class are accessible from outside code. “Outside code” is a member function of another class or the main. Private member variables and functions of a class are accessible only from member functions (public or private) of the same class. It’s an error to access a private member variable or function of a class from outside code.

Public vs. Private, cont’d Make public only what is necessary for outside code to use objects of your class. Public members constitute the interface to the class. Private member variables and functions are effectively hidden from outside code.

Public vs. Private, cont’d Private members make your code more flexible. Hide the implementation of your class. As long as you don’t change the interface to your class (the public members), you can change its implementation (the private members) without affecting outside code that uses objects of the class. Careful class design with public and private members allow you to create abstract data types. Demo

Separate Compilation Put each class declaration in a separate .h header file. By convention, name the file after the class name. Any other source file that uses the class must #include the class header file. A class header file therefore is the interface that the class presents to users of the class. Put the implementations (definitions) of the member functions in a separate .cpp file.

Separate Compilation, cont’d Birthday3.h class Birthday { public:     /**      * Default constructor.      */     Birthday();      * Constructor.      * @param y the year      * @param m the month      * @param d the date     Birthday(int y, int m, int d);     int get_year() const;     int get_month() const;     int get_date() const;     void set_year(const int y);     void set_month(const int m);     void set_date(const int d);     /**      * Print a birthday.      */     void print(); private:     int year, month, date; };

Separate Compilation, cont’d Birthday3.cpp #include <iostream> #include "Birthday3.h" using namespace std; Birthday::Birthday() : year(0), month(0), date(0) {} Birthday::Birthday(int y, int m, int d) : year(y), month(m), date(d) {} int Birthday::get_year()  const { return year; } int Birthday::get_month() const { return month; } int Birthday::get_date()  const { return date; } void Birthday::set_year(const int y)  { year = y; } void Birthday::set_month(const int m) { month = m; } void Birthday::set_date(const int d)  { date = d; } void Birthday::print() {     cout << month << "/" << date << "/" << year << endl; }

Separate Compilation, cont’d BirthdayTester3.cpp #include "Birthday3.h" int main() {     Birthday bd1;     Birthday bd2(1981, 9, 2);     Birthday *pbd1 = new Birthday();            // call default constructor     Birthday *pbd2 = new Birthday(1981, 9, 2);  // call constructor     bd1.print();     bd2.print();     pbd1->print();     pbd2->print();     (*pbd2).print();     delete pbd1;     delete pbd2;     return 0; } 0/0/0 9/2/1981

Quiz Quiz 3 – 2019 Feb 21

Static Member Variables A static member variable of a class belongs to the class itself and not to an object of the class. A static member variable is shared by all objects of the class. A static member variable is global to all objects created from the class. If a static member variable is public, then outside code must use the class name and the scope resolution operator in order to access it.

Static Member Variables, cont’d Birthday4.h class Birthday { public: ...     /**      * Count of all birthday objects.      */     static int count; }; 0/0/0 9/2/1981 There were 4 birthdays created. Birthday4.cpp int Birthday::count = 0; Birthday::Birthday() : year(0), month(0), date(0) {     count++; } Birthday::Birthday(int y, int m, int d) : year(y), month(m), date(d) cout << "There were " << Birthday::count     << " birthdays created." << endl; BirthdayTester4.cpp

Member Functions A member function of a class is applied to a single object of that class. That object is implicitly the function’s first parameter. Examples: Member function print() is first applied to the single Birthday object bd2, and then it is applied to the single Birthday object pointed to by pbd2. Birthday bd2(1981, 9, 2); Birthday *pbd2 = new Birthday(1981, 9, 2); bd2.print(); pbd2->print(); (*pbd2).print();

Static Member Functions A static member function of a class is not applied to any particular object of the class. If the static function is public, the class name and the scope resolution operator is required if the function is called by outside code. A static member function does not have direct access to any regular members (public or private) of the class, only to the static members.

Static Member Functions, cont’d class Birthday { public:     ...     int static get_count();     /**      * Calculate how many years apart from another birthday.      * @parm other the other birthday.      * @return the number of years apart.      */     int years_apart_1(const Birthday *other);      * Calculate how many years apart are two birthdays.      * @parm pbd1 the first birthday.      * @parm pbd2 the other birthday.     int static years_apart_2(const Birthday *pbd1, const Birthday *pbd2); private:     int year, month, date;     static int count; }; Birthday5.h Not static Static

Static Member Functions, cont’d Birthday5.cpp int Birthday::get_count() { return count; } ... int Birthday::years_apart_1(const Birthday *other) {     return abs(year - other->year); } int Birthday::years_apart_2(const Birthday *bd1, const Birthday *bd2)     return abs(bd1->year - bd2->year); This year minus the other year. Difference between two years.

Static Member Functions, cont’d BirthdayTester5.cpp #include <iostream> #include "Birthday5.h" int main() {     Birthday *pbd1 = new Birthday(1975, 1, 1);     Birthday *pbd2 = new Birthday(1981, 9, 2);     pbd1->print();     pbd2->print();     cout << "There were " << Birthday::get_count()          << " birthdays created." << endl;     cout << "They are " << pbd1->years_apart_1(pbd2)          << " years apart." << endl;     cout << "They are " << Birthday::years_apart_2(pbd1, pbd2)     delete pbd1;     delete pbd2;     return 0; } 1/1/1975 9/2/1981 There were 2 birthdays created. They are 6 years apart.

Friend Functions A class can give special privileges to an outside function and allow that function access to its private members. Declare such friend functions inside the class declaration, but they are not member functions of the class. Because a friend function is not member function of the class, you do not apply it to a particular object of the class.

Friend Functions, cont’d Birthday6.h class Birthday { public: ...     /**      * Determine whether or two birthdays are equal.      * @parm pbd1      */     friend bool equal(const Birthday *pbd1, const Birthday *pbd2); private:     int year, month, date;     ... } It doesn’t matter whether you declare a friend function in the public or the private section of your class.

Friend Functions, cont’d bool equal(const Birthday *pbd1, const Birthday *pbd2); int main() {     Birthday *pbd1 = new Birthday(1975, 1, 1);     Birthday *pbd2 = new Birthday(1981, 9, 2);     Birthday *pbd3 = new Birthday(1975, 1, 1);     pbd1->print(); cout << " and ";     pbd2->print(); cout << " are equal: ";     cout << boolalpha << equal(pbd1, pbd2) << endl;     pbd3->print(); cout << " are equal: ";     cout << boolalpha << equal(pbd1, pbd3) << endl;     delete pbd1;     delete pbd2;     delete pbd3;     return 0; } BirthdayTester6.cpp bool equal(const Birthday *pbd1, const Birthday *pbd2) {     return    (pbd1->year  == pbd2->year)            && (pbd1->month == pbd2->month)            && (pbd1->date  == pbd2->date); } 1/1/1975 and 9/2/1981 are equal: false 1/1/1975 and 1/1/1975 are equal: true

Operator Overloading It is possible to overload a C++ operator to give it additional meaning. For example, we can overload the subtraction operator “-” to calculate the difference in years between this Birthday object and another Birthday object .

Operator Overloading, cont’d Birthday7.h class Birthday { public: ...     /**      * Calculate how many years apart from another birthday.      * @parm other the other birthday.      * @return the number of years apart.      */     int operator -(const Birthday& other); } int Birthday::operator -(const Birthday& other) {     return abs(year - other.year); } Birthday7.cpp

Operator Overloading, cont’d BirthdayTester7.cpp #include <iostream> #include "Birthday7.h" int main() {     Birthday bd1(1975, 1, 1);     Birthday bd2(1981, 9, 2);     int diff = bd1 - bd2;     bd1.print(); cout << " and ";     bd2.print(); cout << " are ";     cout << diff << " years apart." << endl;     return 0; } 1/1/1975 and 9/2/1981 are 6 years apart.

Operator Overloading, cont’d You can also make an overloaded operator a friend function. Birthday8.h class Birthday { public: ...     /**      * Calculate how many years apart are two birthdays.      * @parm pbd1 the first birthday.      * @parm pbd2 the other birthday.      * @return the number of years apart.      */     friend int operator -(const Birthday& bd1, const Birthday& bd2); } int operator -(const Birthday& bd1, const Birthday& bd2) {     return abs(bd1.year - bd2.year); } Birthday8.cpp

Operator Overloading, cont’d BirthdayTester8.cpp #include <iostream> #include "Birthday8.h" int main() {     Birthday bd1(1975, 1, 1);     Birthday bd2(1981, 9, 2);     int diff = bd1 - bd2;     bd1.print(); cout << " and ";     bd2.print(); cout << " are ";     cout << diff << " years apart." << endl;     return 0; } 1/1/1975 and 9/2/1981 are 6 years apart.

Overload the << Operator You can overload the output stream extraction operator << class Birthday { public: ...     /**      * Print a birthday in the format mm/dd/yy.      * @parm os the output stream.      * @parm bd the birthday object to print.      * @return the output stream.      */     friend ostream& operator <<(ostream& os, const Birthday& bd); } Birthday9.h Returning ostream& allows you to chain the operator: outs << a << b << c ostream& operator <<(ostream& os, const Birthday& bd) {     cout << bd.month << "/" << bd.date << "/" << bd.year;     return os; } Birthday9.cpp

Overload the << Operator, cont’d BirthdayTester9.cpp #include <iostream> #include "Birthday9.h" int main() {     Birthday bd1(1975, 1, 1);     Birthday bd2(1981, 9, 2);     int diff = bd1 - bd2;     cout << bd1 << " and " << bd2 << " are "          << diff << " years apart." << endl;     return 0; } 1/1/1975 and 9/2/1981 are 6 years apart.