Introduction to Object
Introduction to Object CSE 283
Popular in Course
Popular in Computer Engineering
This 10 page Class Notes was uploaded by David Mayert on Wednesday October 21, 2015. The Class Notes belongs to CSE 283 at Syracuse University taught by Staff in Fall. Since its upload, it has received 63 views. For similar materials see /class/225565/cse-283-syracuse-university in Computer Engineering at Syracuse University.
Reviews for Introduction to Object
Report this Material
What is Karma?
Karma is the currency of StudySoup.
You can buy or earn more Karma at anytime and redeem it for class notes, study guides, flashcards, and more!
Date Created: 10/21/15
CSE 283 Class Notes for Midterm The midterm covers CC object oriented design and a bit on the Standard Template Library 1 vocabularyquestions Questions you should be able to answer What is a class What is an object What is encapsulation What is inheritance What is an operator What is overloading What is operator overloading What is a data member What is a member function What is a public interface What is information hiding What is a constructor Also what is a default constructor What does the copy constructor do What is a destructor What does the assignment operator do When do you use versus gt What s the difference between the public and private tags What does the this keyword refer to What is a friend function Where is friendship declared Why would you use a templated function What is the difference between a copy constructor and an assignment operator What are access rights What s the difference between static and dynamic memory allocation Why would you pick a linked list implementation over an array implementation What s the difference between call by reference and call by value Note member function and method are synonymous 2 printfscanf versus coutcin In C to display information to the screen and to read information from the keyboard we use the printf and scanf functions C provides a cleaner solution by viewing the screen and keyboard as data streams this abstraction extends to files as well The cout and cin streams in C provide the same functionality as printf and scanf For example the C code include ltstdiohgt need when using printf and scanf int main int age printf enter your age scanf d ampage return 0 Is equivalent to the C code include ltiostreamgt needed when using cin and cout using namespace std int main int a e cout ltlt enter your age cin gtgt age return 0 3 mallocfree versus newdelete Dynamic memory allocation happens during runtime when the program asks the operating system to set aside a chunk of memory for its use When the program is done with a chunk of memory it tells the operating system that it is finished with the memory In C these two tasks are accomplished with malloc and free The malloc function requests the memory from the operating system and returns a pointer to that memory to the program When freeing the memory you pass the pointer to the allocated memory to the free function C provides a cleaner implementation for requesting and relinquishing dynamic memory The new and delete functions provide the same functionality as malloc and free For example the C code include ltstdiohgt include ltstdlibhgt int main int ages pointer ages intmallocsizeofint 3 allocates an array of 3 integerst ages0 l7 agesl 18 ages2 21 printf ages d d dn ages0 agesl ages2 freeages returns memory to operating system return 0 Is equivalent to the C code include ltiostreamgt using namespace std int main int ages pointer ages new int3l allocates an array of 3 integers ages0 l7 agesl 18 ages2 21 cout ltlt ages ltlt agesO ltlt ltlt agesl ltlt ltlt ages2 ltlt endl delete ages we need the H when deleting arrays return 0 4 scope Scope is a term that indicates where a variable exists in a program There are four different scope areas global 7 exists everywhere in a program for the entire run of the pro ram within a function 7 exists everywhere within a function and exists only for the duration of the function call within a class or structure 7 exists everywhere within a classbtruct and their object and only exists as long as the object exists within a construct 7 exists everywhere within a construct and exists while code within the construct is being run W NH As an example consider the following code include ltiostreamgt using namespace std int myGlobalScope 42 myGlobalScope has global scope void Funcl int myFuncScope myFuncScope has function scope cout ltlt myGlobalScope ltlt myGlobalScope ltlt endl we can use myGlobalScope within a function because it has global scope and is therefore available anywhere myFuncScope 84 myGlobalScope cout ltlt myFuncScope ltlt myFuncScope ltlt endl we should get myFuncScope2 for output we have left the function at this point so we no longer have access to myFuncScope class Cl private int myClassScope myClassScope has class scope public void DoStuff myClassScope 3 myGlobalScope we can still use myGlobalScope we have left the class definition at this point so we no longer have access to myClassScope int main int j for j 0 339 lt5 jgtl int myConstructScope myConstructScope has construct scope 7 in this case we are in the forloop construct myConstructScope j j cout ltlt myConstructScope ltlt endl myConstructScope is no longer accessible because we have left the forloop C0nstruct return 0 5 static Local variables declared with the keyword static are known only in the function in which they are defined but static variables retain their values when the function exits The next time the function is called the static local variables contain the values they had when the function last exited For example include ltiostreamgt using namespace std void Func static int cnt 0 one time initializer cout ltlt cnt ltlt cnt ltlt t cnt l int main Func Func Func output 0 l 2 return 0 The concept of static can be extended to classes A static class variable represents classwide information Static data members have class scope A class s static members exist even when no objects of that class exist For example include ltiostreamgt using namespace std class Student private string name int id public static int cnt Studentconst string ampn int i name n id i 1 int Studentzzcount 0 One time initializer int main cout ltlt Student count ltlt endl output 0 Student s1 bi11 1111 Student 52 kim 2222 cout ltlt Student count ltlt endl output 2 cout ltlt s1count ltlt endl output 2 cout ltlt s2count ltlt endl output 2 return 0 l Since the static variable exists even when no objects ofthe class exist we can get at it by calling Studentxcount that is proceed the static variable with the name of the class it belongs to Once we have objects of the Student class we can access countjust like any other public component of the class for example sl count 6 pointersreferences Everyone s favorite subject First pointer variables contain memory addresses as their values We typically draw pointer as a box with an arrow coming out of it which ends at the block ofmemory the pointer points at Pointers should be initialized either when they are declared or in an assignment statement A pointer may be initialized to 0 NULL or any address A pointer with the value 0 or NULL points to nothing The amp or address operator us an operator that returns the address of its operand For example int y 5 int yPtr ampy The second line assigns the address ofthe variable y to the pointer variable yPtr Variable yPtr is then said to point to y The operator commonly referred to as the dereferencing operator returns the value at the memory location pointed to by a pointer For example cout ltlt y ltlt t ltlt yPtr ltlt endl The above line produces 5 5 as output The amp and operators are inverses of one another Pointers are used then calling by reference in functions Pointers and arrays may be used almost interchangeably An array name can be thought of as a constant pointer A reference is an alias for its corresponding variable References are often used in callbyreference function arguments in C To indicate that a function parameter is passed by reference simply follow the parameter s type in the function prototype by amp For example include ltiostreamgt using namespace std void Funcint ampaRef aRef 10 l int main int a 17 cout ltlt 51 ltlt a ltlt endl Func a cout ltlt 51 ltlt a ltlt endl return 0 The program output is al 7 on the first line and a27 on the second line Therefore a must have been passed by reference 7 struct versus class In C you define an abstract data type by using the struct keyword For example struct Course char name7 int section int creditHourS l This defines a record that contains the name ofa course as a string a null terminated array of characters the course s section number as an integer and the number of credit hours also as an integer The structure only defines the fields and their corresponding data types it does not define any operations that may be performed on those fields The above struct can be rewritten as a class as follows class Course public char name7 int section int creditHourS l This is the minimum you would have to do to convert to a class However the power of classes is pretty much untapped here 8 more on classes To begin to harness the power of classes you will want to employ encapsulation information hiding Modifying the above class definition to hide its data members is achieved as follows class Course private char name7 int section int creditHourS l While this effectively hides name section and credit hours it does so too well 7 we have no access to these data members at all Access is achieved by adding member functions methods as part of the class s public interface For instance class Course private char name7 int section int creditHourS public void SetNamechar n strcpyname n void SetSectionint s section s void SetCreditHoursint ch creditHours ch l These publicly defined methods make up the classes current public interface They allow us to set the name section and credit hours Unfortunately we don t have a way to get the values back We must therefore extend the public interface For instance class Course private char name7 int section int creditHourS public void SetNamechar n strcpyname n void SetSectionint s section 7 s l void SetCreditHoursint ch creditHours ch char GetName const return name int GetSection const return section int GetCreditHours const return creditHours l Notice the use ofthe const keyword after each get function s parameter list This means that objecm of type const Course can call these functions Constant objects of type Course cannot call the set functions because the object s members would be modified It s a good idea to provide a default constructor for classes We can have a constructor that takes a name section and credit hours but is also a default constructor In order for this to work we need to provide default values for all constructor parameters For instance class Course private char name7 int section int creditHours public void SetNamechar n strcpyname n void SetSectionint s section s void SetCreditHoursint ch creditHours ch char GetName const return name int GetSection const return section int GetCreditHours const return creditHours Coursechar n int s 0 int ch strcpyname n section s creditHours ch l Rememberthe name of the constructor matches the name of the class and constructors don t have return types We can now set the name section and credit hours of an object of type Course when that object is declared or use the default values We can retrieve any ofthese values using the Get accessor functions We can also set any of these values using the Set accessor functions Now we would also like to have a way of copying an object of class course into a new object of class course We do this using the copy constructor For instance class Course private char name7 int section int creditHours public void SetNamechar n strcpyname n void SetSectionint s section s void SetCreditHoursint ch creditHours ch char GetName const return name int GetSection const return section int GetCreditHours const return creditHours Coursechar n int s 0 int ch O strcpyname n section s creditHours ch l Courseconst Course ampc strcpyname cname section csection creditHours ccreditHours l The parameter to the copy constructor is a constant reference to an object of type Course Constant references are an efficient was ofpassing objects 7 you get the memory efficiency of a pointer and the compiler keeps you from modifying the object s data Remember the copy constructor is a true constructor it will only be called when an object of type Course is being created and only when another object of type Course is passed as a parameter We would therefore also like a way to copy the contents of an existing Course object into the contents of another existing Course object This is accomplished by overloading the assignment operator For instance class Course private char name 7 int section int creditHours public void SetNamechar n strcpyname n void SetSectionint s section s void SetCreditHoursint ch creditHours ch char GetName const return name int GetSection const return section int GetCreditHours const return creditHours Coursechar n int s 0 int ch O strcpyname n section s creditHours ch l Courseconst Course ampc strcpyname section creditHours l cname csection ccreditHourS const Course ampoperatorconst Course ampc strcpyname cname section csection creditHours csreditHours return this l Notice that the assignment operator returns a reference to the course being modified 7 that is why we return this The this pointer refers to the object being modified By having a return type we can string together assignments such as abc Constructors are called when an object is created To satisfy our need for symmetry destructors are called when an object is destroyed For our Course class we don t really need to implement a destructor but for the sake of the example here goes class Course private char name7 int section int creditHours public void void int GetSectionO SetNamechar n strcpyname n l SetSectionint s section s SetCreditHoursint ch creditHours GetName const return name const return section ch l int GetCreditHours const return creditHours Coursechar n int s 0 int ch O strcpyname n section s creditHours ch l Courseconst Course ampc strcpyname section creditHours l const Course amp strcpyname section creditHours cname section ccreditHourS C operatorconst Course ampc cname ection ccreditHourS CS return this l Course cout ltlt do nothing destructorn l Remember the destructor takes on the name of the class prefixed with a N character The destructor has no return type You would typically free up system resources associated with the object being destroyed 9 template functions The only reason we talked about template functions was to lead in to the Standard Template Library You need to have at least a rudimentary understanding of what templates are Here s a brief example to get you used to the notion Let s say that we want to develop a swap function that is independent of the data type Instead of writing overloaded functions for each data type your program might want to swap we can use a template function For instance template ltclass Tgt void SwapT thingl T thingZ T temp temp thingl thingl thingZ thingZ temp l All function templates begin with the keyword template followed by a list of formal parameters to the function template enclosed in angle brackets lt and gt39 each formal parameter that represents a type must be preceded by the keyword class whether the type is actually a class or not So in our main we might have something that looks like int main int a 3 b double 3 7 Swapa b Swapc d When the compiler encounter the line Swapa b39 it knows that a function template has been provided for Swap As such it determines that a s data type matches b s which it does then it generates an integer version of the Swap function at compile time As such the following function now exists this function is compiler generated void Swapint thingl int thingZ int temp temp thingl thingl thingZ thingZ temp l When the compiler then encounter the line Swapc d39 it still knows that a function template has been provided for Swap Again it determines that c s data type matches d s then it generates a double version of the Swap function at compile time As such the following function now exits this function is also compiler generated void Swapdouble thingl double thingZ double temp temp thingl thingl thingZ thingZ temp Since C allows for overloading of operators and functions there is no problem having two functions named Swap 7 they have different data types in their parameter lists so they can be distinguished The astute observer will recognize that the compiler is merely substituting the templates formal parameter T with the data type of the calling arguments int in the first case double in the second This concept extends to classes as well 7 we can have class templates So when we use the Standard Template Library what we are really doing is asking the compiler to generate a class from a class template When we use code like listltintgt listl 39 the compiler generates an integer list class and listl is an object of that class 10 some 8 TL You should be familiar with the quotlistquot template container from the Standard Template Library Minimally know that the quotlistquot template container is implemented under the hood as a linked list You should know how to declare a new list For instance the following declarations declare an integer list and a list ofCourses list mylntList list myCourseList Notice the template syntax You should also be familiar with some ofthe operations on lists such as a size returns number of elements in the list pushifront adds a new element at the front of the list popifront removes the element at the front of the list pushiback adds a new element at the back ofthe list popiback removes the element at the back ofthe list clear removes all elements erase erases the element pointed to by aniterator front returns the element at the front of the list back returns the element at the back ofthe list You should also be confoItable with the concept of iterators As an example consider the following code include ltlistgt include ltiostreamgt using namespace std int main listltintgt mylntList mylntListpush7front42 mylntListpush7frontl6 mylntListpush7back98 Q what are the list elements at this point A 42 16 98 not in that order cout ltlt size ltlt mylntListsize ltlt list listltintgtzziterator i for i myIntListbegin i l myIntListend i cout ltlt i lt 39 39 l cout ltlt endl Q what is the output A size3 listl6 42 98 i mylntListbegin Q what is the iterator i pointing at A i points at 42 mylntListerasei Q what does the list contain now A 16 98 cout ltlt mylntListback ltlt 39 39 cout ltlt mylntListfront ltlt endl Q what is the output A 98 16 mylntListpop7front mylntListpop7back Q what does the list contain A it is empty could have just called mylntListclear0 return 0 11 object oriented design You should be familiar with the steps ofthe object oriented design method see lecture 5 ClassObject Model analyze the problem statement for nouns and verbs list them all minimize and categorize remove nouns that don t add to the problem understanding identify nouns that are classes identify nouns that are attributes identify implied attributes create an object dictionary provides a set ofterrninology analyze verbs and verb phrases for relationships between classes a draw the model ie the classes their attributes member functions and relationships between classes Dynamic Model identify any actions document the main scenario document variations on the main scenario I I a document error scenarios create the user s manual generate a time trace Functional Model from the above models identify all functions that are needed determine inputs and outputs of each function document what each function does identify internal elements needed by each function graph the data flow through the function how inputs become outputs
Are you sure you want to buy this material for
You're already Subscribed!
Looks like you've already subscribed to StudySoup, you won't need to purchase another subscription to get this material. To access this material simply click 'View Full Document'