1 / 33

Today’s Objectives

14-Jun-2006. Today’s Objectives. Announcements Save all the cpp and h files that you create in this course

eadoin
Download Presentation

Today’s Objectives

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. 14-Jun-2006 Today’s Objectives • Announcements • Save all the cpp and h files that you create in this course • Quiz #2 is Monday, 19-Jun – over material in Ch. 6, 7, and 9Be sure to study arrays, ways to pass arguments to functions, pointers, C-style strings, instantiating objects and using member functions, dynamically allocating memory for an object using “new” and using a pointer to an object • Structures • Keeping track of data • C-style structure • Classes: a Deeper Look, Part 1 • Class • The public interface • Encapsulation • Information hiding • Constructor • Destructor • Separating interface and implementation • Inline functions • Default memberwise assignment

  2. Structs Chapter 22.2

  3. Structs Keeping Track of Data • Variables are used to keep track of data in the computer’s memory. • Regular variable – keeps track of the value of one data element • Pointer variable – keeps track of the memory address of a data element • Array – keeps track of a collection of related data elements of the same data type

  4. Structs (Deitel, 1058–1061) Struct • Struct – keeps track of a collection of related data elements that may have different data types • Each element is called a “member” or “field” • Each field has a name and data type • Defining a struct struct Person{ int ID; string firstName; string lastName; }; Name Fields – always “public” Remember the ‘;’ !

  5. Structs (Deitel, 1058–1061) Using Structs • The struct’s definition creates a new data type • We can use it to declare a structure variable Person alan; • To initialize the struct variable, each field can be accessed by the “.” operator alan.ID = 1001; alan.firstName = "Alan"; alan.lastName = "Turing"; cout << alan.firstName << endl;

  6. Structs Dynamically Allocated Structs • We can dynamically create a struct with “new” • Use “new” to allocate memory and return a pointer Person *pDonald = new Person; • When a pointer is used to get values stored in a struct, each field must be accessed by the “->” operator pDonald->ID = 1005; pDonald->firstName = "Donald"; pDonald->lastName = "Knuth"; cout << pDonald->firstName << endl; delete pDonald;//Always delete after new • Optional syntax: cout << (*pDonald).firstName;

  7. Structs Struct Exercises Handout

  8. Classes: a Deeper Look, Part 1 Chapter 9

  9. Classes, Part 1 (Deitel, 77–110) Class • Another collection of related data elements that may have different data types • Like a struct, but better – a class also includes all the operations that can be performed with its data • Definition • Class = a collection of related elements that may have different data types and the operations that can be performed on them

  10. Classes, Part 1 (Deitel, 77–110) Declaring a Class Name class Person{ public: Person(); int getID(); void setID( int id ); string getFirstName(); void setFirstName( string nm ); string getLastName(); void setLastName( string nm ); string toString(); private: int ID; string firstName; string lastName; }; Member functions (also called methods or operations) Data Members Remember the ‘;’ !

  11. Classes, Part 1 (Deitel, 77–110) Using a ClassInstantiate an object • After a class is declared, it creates a new data type • We can use it to “declare a variable,” but we use a different terminology. We say that a class is used to create an “object” that is an instance of the class. • Instantiating an object int main(){ Person donald; } Object

  12. Classes, Part 1 (Deitel, 77–110) Using an ObjectCall the member functions • All of the operations that an object can perform are defined by its public member functions, called its “public interface” int main(){ Person donald; donald.setFirstName("Donald"); donald.setLastName("Knuth"); cout << donald.toString(); } Argument Object Parentheses are required “Dot” operator Member function

  13. Classes, Part 1 (Deitel, 77–110) The Public Interface • All of the public member functions are collectively called the “public interface” of the class • The public interface is defined first in the design stage • After the class implementation is finished, the user of the objects of the class has an outside view, and has access only to the public interface • The user knows what the objects of the class can do because the names of the member functions, the return data type, and the argument data types are all public

  14. Classes, Part 1 (Deitel, 77–110) Information Hiding • The implementation of the class is not always accessible • The user does not know how the member functions work and does not need to know • Data members are always made private • The user of an object in your program cannot change the data by accessing it directly • So that we can control how the data can be changed • We can validate a requested change • Example: The ID member cannot be a negative number, it has to be an integer, and it should not be a number that is already in use • Also, so we can control how we store the data inside the class • Example: We may decide to store the ID as a string instead of an int • The user of an object can still get the data and change it, but only by using a public member function

  15. Classes, Part 1 (Deitel, 77–110) Encapsulation • One of the three principle features of object-oriented programming • Means that we keep both the data and the operations that can be done with that data inside a single entity, the class • In addition, the user of the objects of the class has an outside view, and has access only to the operations.

  16. Classes, Part 1 (Deitel, 77–110) Advantages Advantages to encapsulation in a single entity that has a public interface: • Teamwork during development is supported – Each member of the development team can develop a class independently. When a developer’s class needs to interact with a class developed by another team member, the first developer only needs to know its public interface • Easy to improve your program – The programmer has the freedom to implement the operations and change them in any way, as long as the public interface works correctly • Reuse and program maintenance are easier • Easier for future programmers to understand the way it works • Easier to make improvements, e.g. speeding up a searching function by storing the data in a sorted array instead of an unsorted array

  17. Classes, Part 1 (Deitel, 491) Private Member Functions • Not all member functions have to be public • If a member function is only used by other functions in the class, it can be private • Called utility functions

  18. Classes, Part 1 (Budd) Message Passing • Using an object’s member functions is called “message passing” • The user of the object sends a message to the object, asking it to perform an action • Write the name of the receiver of the message, the dot operator, the message, and any arguments that are required Person james;//instantiating an object james.setID( 1006 );//sending a message to james james.setFirstName( "James" ); james.setLastName( "Gosling" ); cout << james.toString() << endl;

  19. Classes, Part 1 (Deitel, 77–110, 493–502) Constructor • Public member function with the same name as the class and with no return value • Called automatically to initialize the data members whenever an object is instantiated • Implement it in one of two ways 1. Either assign values in the constructor body Person( int id = 0, string fn = "", string ln = "" ){ setID(id); setFirstName(fn); setLastName(ln); } 2. Or use an initializer list Person( int id = 0, string fn = "", string ln = "" ) : ID(id), firstName(fn), lastName(ln) { } Appropriate if the set function does more than simple assignment Initializer list

  20. Classes, Part 1 (Deitel, 77–110, 493–502) Instantiating an object with default values • When an object is instantiated, the constructor automatically initializes the data members • The constructor will initialize the data members to default values if the object is instantiated with this syntax: Person james; //Invokes the default constructor • If there is a version of the constructor with parameters, then the initial values can be passed as arguments Person james( 1006, "James", "Gosling" );

  21. Classes, Part 1 (Deitel, 550–552) Creating a pointer to an object with “new” • We do not always know how many objects we need • We can create objects as we need them by using “new” to allocate memory dynamically. Person *pJames = new Person; “new” always returns a pointer • Reminder: Always use “delete” when you don’t need the pointer anymore. delete pJames;

  22. Classes, Part 1 (Deitel, 550–552) Using a member function with a pointer to an object • When a pointer is used to refer to an object in memory, the member functions can be called by the “->” operator pJames->setFirstName( "James" ); Use with a pointer

  23. Classes, Part 1 (Deitel, 77–110, 493–502) Using new in the Constructor • If a class will use an array to store its data, we can represent the array as a pointer variable, and then allocate memory for it dynamically. What is the advantage? • The memory can be allocated by using new in the constructor class PersonList{ private: Person *pMyData; //This will point to an array public: PersonList( int cap = 10 ) :sz(0),capacity(cap){ pMyData = new Person[capacity]; //Allocates memory } /*Other code left out ... */ };

  24. Classes, Part 1 (Deitel, 499–502) Destructor • Public member function with the same name as the class, but with a tilde character (~) in front of the name • No return value • No parameters • Automatically called when the class goes out of scope • Needed only if the class uses “new” or otherwise allocates resources class PersonList{ private: Person *pMyData; //This will point to an array public: PersonList( int cap = 10 ) :sz(0),capacity(cap){ pMyData = new Person[capacity]; //Allocates memory } ~PersonList(){ //Destructor delete[] pMyData; //Frees the memory } /*Other code left out ... */ };

  25. Classes, Part 1 Example class Person{ public: Person( string nm="" ):name(nm){ cout << "Person constructor called\n"; } ~Person(){ cout << "Person destructor called\n"; } private: string name; }; void change( Person p ){ cout << "Inside function change\n"; } int main(){ cout << "Main is creating a Person object" << endl; Person alice("Alice"); cout << "\nMain is calling the change function" << endl; change(alice); cout << "\nNow we're back in main." << endl; }

  26. Classes, Part 1 (Deitel, 489) Inline Functions • Placing the function definition inside the class declaration instead of defining it externally • Appropriate only for small functions • Program execution is speeded up when member functions are defined as inline functions • The compiler will have the option of placing the code for the function inside the main program code instead of making a function call

  27. Classes, Part 1 (Deitel, 486, 489) Separate Implementation Outside of and below the declaration of the member function in the class string Person::toString(){ return firstName + " " + lastName; } Class name Binary scope operator Return type Member function name Implementation

  28. Classes, Part 1 (Deitel, 486, 489) Separate Files forInterface and Implementation • In C++, this is the normal approach • Declaration goes in the header file (Person.h) – this part is considered the “interface” • Definition goes in the source file (Person.cpp) – this part is considered the “implementation” • Advantages • Smaller header files – header files are included with the source file • Developer can hide the implementation details main.cpp Person.h Person.cpp #include "Person.h" int main(){ Person james; james.setName("James"); } #include <string> using std::string; class Person{ public: void setName(string); string getName(); private: string name; }; #include "Person.h" string Person::getName() { return name; } void Person::setName(string nm) { name = nm; }

  29. Classes, Part 1 (Deitel, 506–508) Default Memberwise Assignment • The assignment operator (=) can be used to assign one object to another of the same type Person temp; Person doe( 1008, "John", "Doe"); temp = doe; • A copy of each data member in the object on the right is assigned to the object on the left • Will not work properly if one of the data members is a pointer created with “new”

  30. Classes, Part 1 (Deitel, 506–508) Passing Objects as Arguments • Default memberwise assignment commonly occurs when an object is passed by value as a function argument. A special constructor called the “copy constructor” is called automatically. • Also occurs when an object is returned from a function by value • With objects, pass-by-value is very inefficient • Objects may occupy a lot of memory, so making a copy is wasteful • Making a copy of an object is time-consuming

  31. Classes, Part 1 (Deitel, 506–508) Objects as Reference Arguments • Objects should always be passed to functions using pass-by-reference • With pass-by-reference, no copy of the object passed as an argument is made • The original values stored in the object are changed when the function changes the object passed to it as an argument • If the object must not be changed, then use const bool search( const List myList ){ //code to search the list }

  32. Classes, Part 1 Class Exercises Handout

  33. References Budd, T., An Introduction to Object-Oriented Programming, Third Edition. Boston: Addison Wesley, 2002. Deitel, H. M., and P. J. Deitel, C++ How to Program, Fifth Edition. Upper Saddle River, NJ: Prentice Hall, 2005. Goodrich, M. T., R. Tamassia, and D. Mount, Data Structures and Algorithms in C++. Hoboken, NJ: John Wiley & Sons, Inc., 2004.

More Related