Copy Constructors and Assignment Operators

Size: px
Start display at page:

Download "Copy Constructors and Assignment Operators"

Transcription

1 CS106L Winter Handout #17 Feburary 25, 2008 Copy Constructors and Assignment Operators Introduction Unlike other object-oriented languages like Java, C++ has robust support for object deep-copying and assignment. You can choose whether to pass objects to functions by reference or by value, and can assign objects to one another as though they were primitive data types. C++ handles object copying and assignment through two functions called copy constructors and assignment operators. While C++ will automatically provide these functions if you don't explicitly define them, in many cases you'll need to manually control how your objects are duplicated. This handout discusses copy constructors and assignment operators, including both high-level concepts and practical implementation techniques. Assignment versus Initialization Before discussing copy constructors and assignment operators, let's first discuss the subtle yet crucial difference between assignment and initialization. Consider the following code snippet: MyClass one; MyClass two = one; Here, the variable two is initialized to one because it is created as a copy of another variable. When two is created, it will go from containing garbage data directly to holding a copy of the value of one with no intermediate step. However, if we rewrite the code as MyClass one, two; two = one; Then two is assigned the value of one. Note that before we reach the line two = one, two already contains a value. This is the difference between assignment and initialization when a variable is created to hold a specified value, it is being initialized, whereas when an existing variable is set to hold a new value, it is being assigned. If you're ever confused about when variables are assigned and when they're initialized, you can check by sticking a const declaration in front of the variable. If the code still compiles, the object is being initialized. Otherwise, it's being assigned a new value. Copy Constructors Whenever you initialize an object, C++ will make the copy by invoking the class's copy constructor, a constructor that accepts another object of the same type as a parameter.

2 Copy constructors are invoked whenever: 1. A newly-created object is initialized to the value of an existing object. 2. An object is passed to a function as a non-reference parameter. 3. An object is returned from a function. Let's consider each of these cases individually. The first case, when new objects are initialized to the value of existing objects, is easiest to see. For example, suppose you write the following code: MyClass one; MyClass two = one; MyClass three = two; Here, since two and three are being initialized to the values of one and two, respectively, C++ will invoke the copy constructors to initialize their values. Although it looks like you're assigning values to two and three using the = operator, since they're newly-created objects, the = indicates initialization, not assignment. In fact, the above code is equivalent to the more explicit initialization code below: MyClass one; MyClass two(one); // Equivalent to the above code. MyClass three(two); // Same here For the second case, consider the following function: void myfunction(myclass parameter) //... Work with parameter... If we write MyClass mc; myfunction(mc); Then the variable parameter inside of myfunction will be initialized to a copy of mc using the copy constructor. In the final case, suppose we have the following function: MyClass myfunction() MyClass mc; return mc; If we call myfunction, then C++ will create a new myclass object that's initialized to mc when myfunction returns. Thus while your code might act like it's transparently moving the object from inside of myfunction to the rest of your code, it's actually making a temporary copy.

3 Assignment Operators While the copy constructor is used to set up a new version of an object that's a duplicate of another object, the assignment operator is used to overwrite the value of an already-created object with the contents of another class instance. For example, the following code will invoke the assignment operator, not the copy constructor: MyClass one, two; two = one; In this case, since two has already been initialized in the previous line, C++ will use the MyClass assignment operator to assign two the value of the variable one. It can be tricky to differentiate between code using the assignment operator and code using the copy constructor. For example, if we rewrite the above code as MyClass one; MyClass two = one; We are now invoking the copy constructor rather than the assignment operator. Always remember that the assignment operator is called only when assigning an existing object a new value. Otherwise, you're using the copy constructor. What C++ Does For You Unless you specify otherwise, C++ will automatically provide objects a basic copy constructor and assignment operator that simply invoke the copy constructors and assignment operators of all the class's data members. In many cases, this is exactly what you want. For example, consider the following class: class MyClass public: /* Omitted. */ private: int myint; string mystring; ; Suppose you have the following code: MyClass one; MyClass two = one; The line MyClass two = one will invoke the copy constructor for MyClass. Since we haven't explicitly provided our own copy constructor, C++ will simply initialize two.myint to the value of one.myint and two.mystring to one.mystring. Since int is a primitive and string has a welldefined copy constructor, this code is totally fine. However, in many cases this is not the behavior you want. Let's consider the example of a class CString that acts as a wrapper for a C string. Suppose we define CString as shown here:

4 class CString public: CString(); ~CString(); // Deallocates the stored string. // Note: No copy constructor or assignment operator private: char *thestring; ; Here, if we rely on C++'s default copy constructor or assignment operator, we'll run into trouble. For example, consider the following code: CString one; CString two = one; Because we haven't provided a copy constructor, C++ will initialize two.thestring to one.thestring. Since thestring is a char *, instead of getting a deep copy of the string, we'll end up with two pointers to the same C string. Thus changes to one will show up in two and vice-versa. This is dangerous, especially when the destructors for both one and two try to deallocate the memory for thestring. In situations like these, you'll need to override C++'s default behavior by providing your own copy constructors and assignment operators. The Rule of Three There's a well-established C++ principle called the rule of three that almost always identifies the spots where you'll need to write your own copy constructor and assignment operator. If this were a math textbook, you'd probably see the rule of three written out like this: Theorem: If a class has any of the following three member functions: Destructor Copy Constructor Assignment Operator Then that class should have all three of those functions. Corollary: If a class has a destructor, it should also have a copy constructor and assignment operator. The rule of three holds because in almost all situations where you have any of the above functions, C++'s default behavior won't correctly manage your objects. In the above example with CString, this was the case because copying the char * pointer didn't actually duplicate the C string. Similarly, if you have a class holding an open file handle, making a shallow copy of the object might cause crashes further down the line as the destructor of one class closed the file handle, corrupting the internal state of all copies of that object. Both C++ libraries and fellow C++ coders will expect that, barring special circumstances, all objects will correctly implement the three above functions, either by falling back on C++'s default versions or by explicitly providing correct implementations. Consequently, you must keep the rule of three in mind when designing classes or you will end up with insidious or seemingly untraceable bugs as your classes start to destructively interfere with each other.

5 Writing Copy Constructors For the rest of this handout, we'll discuss copy constructors and assignment operators through a case study of the DebugVector class. DebugVector is a modified version of the CS106 Vector whose constructor and destructor write creation and destruction information to cout. That way, if you're writing a program that you think might be leaking memory, you can check the program output to make sure that all your DebugVectors are begin cleaned up properly. The class definition for DebugVector looks like this: class Vector public: DebugVector(); DebugVector(const DebugVector &other); // Copy constructor DebugVector &operator =(const DebugVector &other); // Assn. operator ~DebugVector(); ; /* Other member functions. */ private: T *array; int allocatedlength; int logicallength; static const int BASE_SIZE = 16; The syntax for the copy constructor and assignment operator might look a bit foreign. The copy constructor is simply a class constructor that accepts as a parameter a const reference to another instance of the class. The assignment operator, however, is a special type of function called an overloaded operator, a topic we'll cover in more detail next week. For now, you should just take on faith that the function named operator = will redefine what it means to use the = operator in code. The DebugVector is internally implemented as a dynamically-allocated array of elements. We have two data members allocatedlength and logicallength that track the allocated size of the array and the number of elements stored in it, respectively. It also has a class constant BASE_SIZE that represents the base size of the allocated array. The DebugVector constructor is defined as DebugVector<T>::DebugVector() : array(new T[BASE_SIZE]), allocatedlength(base_size), logicallength(0) // Log the creation using some functions from <ctime> time_t currenttime; time(&currenttime); // Fill in the current time. cout << "DebugVector created: " << ctime(&currenttime) << endl; Note that we're initializing array to point to a dynamically-allocated array of BASE_SIZE elements in the initializer list.

6 Similarly, the DebugVector destructor is DebugVector<T>::~DebugVector() delete [] array; array = NULL; // Just to be safe logicallength = allocatedlength = 0; time_t currenttime; time(&currenttime); cout << "Destructor invoked: " << ctime(&currenttime) << endl; Now, let's write the copy constructor. We know that we need to match the prototype given in the class definition, so we'll write that part first: DebugVector<T>::DebugVector(const DebugVector &other) // Our code goes here. Inside the copy constructor, we'll need to do two things. First, we'll need to initialize the object so that we're holding a deep copy of the other DebugVector. Second, we'll need to log the creation information since we're instantiating a new DebugVector. Let's first initialize the object, then handle the logging later. As with a regular constructor, with a copy constructor we should try to initialize as many instance variables as possible in the initializer list, both for readability and speed. In the case of DebugVector, while we can't completely set up the data members in the initializer list, we can still copy over the value of logicallength and allocatedlength. For this handout, however, we'll initialize these variables inside the body of the constructor, since logicallength and allocatedlength are both primitives and thus don't get a performance boost from the initializer list. Thus our copy constructor will look something like this: DebugVector<T>::DebugVector(const DebugVector &other) logicallength = other.logicallength; allocatedlength = other.allocatedlength; // Incomplete, but on the right track Note that although other's logicallength and allocatedlength are private variables, we're allowed to access them freely. This is sometimes known as sibling access and is true of any member function, not just the copy constructor. Now, we'll make a deep copy of the other DebugVector's elements by allocating a new array that's the same size as other's and then copying the elements over. The code looks something like this:

7 DebugVector<T>::DebugVector(const DebugVector &other) logicallength = other.logicallength; allocatedlength = other.allocatedlength; array = new T[allocatedLength]; for(int i = 0; i < logicallength; i++) array[i] = other.array[i]; // Still need to log everything. Interestingly, since DebugVector is a template, it's unclear what the line array[i] = other.array[i] will actually do. If we're storing primitive types, then the line will simply copy the values over, but if we're storing objects, the line calls the class's assignment operator. Notice that in both cases the object will be correctly copied over. This is one of driving forces behind defining copy constructors and assignment operators, since template code can assume that expressions like object1 = object2 will be meaningful. Finally, we need to log the creation of the new DebugVector. If you'll notice, the code for logging the DebugVector's creation is already written for us in the constructor. Unfortunately, unlike other objectoriented languages, in C++, a class with multiple constructors can't invoke one constructor from the body of another. To avoid code duplication, we'll therefore move the logging code into a separate private member function called logcreation that looks like this: void DebugVector<T>::logCreation() time_t currenttime; time(&currenttime); // Fill in the current time. cout << "DebugVector created: " << ctime(&currenttime) << endl; We then rewrite the default constructor for DebugVector to call logcreation, as shown below: DebugVector<T>::DebugVector() : array(new T[BASE_SIZE]), allocatedlength(base_size), logicallength(0) logcreation(); And finally, we insert a call to logcreation into the copy constructor, yielding the final version, which looks like this: DebugVector<T>::DebugVector(const DebugVector &other) logicallength = other.logicallength; allocatedlength = other.allocatedlength; array = new T[allocatedLength]; for(int i = 0; i < logicallength; i++) array[i] = other.array[i]; logcreation();

8 Writing Assignment Operators We've now successfully written a deep-copying copy constructor for our DebugVector class. Unfortunately, writing an assignment operator is significantly more involved than writing a copy constructor. C++ is designed to give you maximum flexibility when designing an assignment operator, and thus won't alert you if you've written a syntactically legal assignment operator that is completely incorrect. For example, consider this legal but incorrect assignment operator for an object of type MyClass: void MyClass::operator =(const MyClass &other) cout << "Sorry, Dave, I can't copy that object." << endl; Here, if we write code like this: MyClass one, two; two = one; Instead of making two a deep copy of one, instead we'll get a message printed to the screen and two will remain unchanged. This is one of the dangers of operator overloading code that looks like it does one thing can instead do something totally different. This next section will discuss how to correctly implement an assignment operator by starting with invalid code and progressing towards a correct, final version. Let's start off with a simple but incorrect version of the assignment operator for DebugVector: /* Many major mistakes here. */ void DebugVector<T>::operator =(const DebugVector &other) logicallength = other.logicallength; allocatedlength = other.allocatedlength; array = new T[allocatedLength]; for(int i = 0; i < logicallength; i++) array[i] = other.array[i]; The most serious error here is the line array = new T[allocatedLength]. When the assignment operator is invoked, this DebugVector is holding on to its own array of elements. However, with this line, we're orphaning our old array and leaking a good deal of memory. To fix this, before we make this object a copy of the one specified by the parameter, we'll take care of the necessary deallocations. If you'll notice, we've already written some of the necessary cleanup code in the destructor. Rather than rewriting this code, we'll decompose out the generic cleanup code into a clear function, as shown here: void DebugVector<T>::clear() delete [] array; array = NULL; logicallength = allocatedlength = 0;

9 We can then rewrite the destructor as DebugVector<T>::~DebugVector() clear(); time_t currenttime; time(&currenttime); cout << "Destructor invoked: " << ctime(&currenttime) << endl; And we can insert this call to clear into our assignment operator as follows: /* Still are some errors here. */ void DebugVector<T>::operator =(const DebugVector &other) clear(); logicallength = other.logicallength; allocatedlength = other.allocatedlength; array = new T[allocatedLength]; for(int i = 0; i < logicallength; i++) array[i] = other.array[i]; Along the same lines, you might have noticed that all of the code after the call to clear is exactly the same code we wrote inside the body of the copy constructor. This isn't a coincidence in fact, in most cases you'll have a good deal of overlap between the assignment operator and copy constructor. Since we can't invoke our own copy constructor, instead we'll decompose the copying code into a member function called copyother as follows: void DebugVector<T>::copyOther(const DebugVector &other) logicallength = other.logicallength; allocatedlength = other.allocatedlength; array = new T[allocatedLength]; for(int i = 0; i < logicallength; i++) array[i] = other.array[i]; Now we can rewrite the copy constructor as DebugVector<T>::DebugVector(const DebugVector &other) copyother(other); logcreation(); And the assignment operator as

10 /* Not quite perfect yet. */ void DebugVector<T>::operator =(const DebugVector &other) clear(); copyother(other); This simplifies the copy constructor and assignment operator and highlights the general pattern of what the two functions should do. With a copy constructor, you'll copy the contents of the other object, then perform any remaining initialization. With an assignment operator, you'll clear out the current object, then copy over the data from another object. However, we're still not done yet. There are two more issues we need to fix with our current implementation of the assignment operator. The first one has to do with self-assignment. Consider, for example, the following code: MyClass one; one = one; While this code might seem a bit silly, cases like this come up frequently when accessing elements indirectly through pointers or references. Unfortunately, with our current DebugVector assignment operator, this code will lead to unusual runtime behavior. To see why, let's trace out the state of our object when its assignment operator is invoked on itself. At the start of the assignment operator, we call clear to clean out the object for the copy. During this call to clear, we deallocate the memory associated with the object and set both logicallength and allocatedlength to zero. Thus our current object looks something like this: int logicallength 0 int allocatedlength 0 T *array NULL Normally this isn't a problem, but remember that we're self-assigning, which means that the object referenced by other is the same object referenced by the this pointer. Consequently, since we erased all the contents of the current object, we also erased the contents of the other object. When we get to the code in copyother, we'll end up duplicating an empty object. The result is that our self-assignment is effectively a glorified call to clear. When writing assignment operators, you absolutely must ensure that your code correctly handles selfassignment. While there are many ways we can do this, perhaps the simplest is to simply check to make sure that the object to copy isn't the same object pointed at by the this pointer. The code for this logic looks like this:

11 /* Not quite perfect yet there's one more error */ void DebugVector<T>::operator =(const DebugVector &other) if(this!= &other) clear(); copyother(other); Note that we check if(this!= &other). That is, we are comparing the addresses of the current object and the parameter. This will determine whether or not the object we're copying is exactly the same object as the one we're working with. Note that we did not write if(*this!= other), since this would do a semantic comparison between the objects, something we'll cover next week when discussing operator overloading. One last note is that code like this isn't required in the copy constructor, since we can't pass an object as a parameter to its own copy constructor. There's one final bug we need to sort out, and it has to do with how we're legally allowed to use the = operator. Consider, for example, the following code: MyClass one, two, three; three = two = one; Since our current assignment operator does not return a value, the above code will not compile. Thus we need to change to our assignment operator so that it returns a value that can be used in future assignments. The final version of our assignment operator is thus /* The CORRECT version. */ DebugVector<T> & DebugVector<T>::operator =(const DebugVector &other) if(this!= &other) clear(); copyother(other); return *this; Note that we're returning *this, the value of the current object. Since the return type is a DebugVector<T> &, we're actually returning a reference to the current object, rather than a deep copy. Since the expression one = two = three is equivalent to one = (two = three), this will work out correctly. One General Pattern Although each class is different, in many cases the default constructor, copy constructor, assignment operator, and destructor will share a general pattern. Here is one possible skeleton you can fill in to get your copy constructor and assignment operator working.

12 MyClass::MyClass() : /* Fill in initializer list. */ additionalinit(); MyClass::MyClass(const MyClass &other) copyother(other); additionalinit(); // Don't set any data members here if possible. MyClass &MyClass::operator =(const MyClass &other) if(this!= &other) clear(); // Note: When we cover inheritance, there's one more step here. copyother(other); return *this; MyClass::~MyClass() clear(); additionalclosedown(); Semantic Equivalence and copyother Strategies Consider the following code snippet: DebugVector<int> one; DebugVector<int> two = one; Here, we know that two is a copy of one, so the two objects should behave identically to one another. For example, if we access an element of one, we should get the same value as if we had accessed an element of two and vice-versa. However, while one and two are indistinguishable from each other in terms of functionality, their memory representations are not identical because one and two point to two different dynamically-allocated arrays. This raises the distinction between semantic equivalence and bitwise equivalence. Two objects are said to be bitwise equivalent if they have identical binary representations in memory. For example, any two ints with the value 137 are bitwise equivalent, and if we define a pointt struct as a pair of ints, any two pointts holding the same location will be bitwise equivalent. Two objects are semantically equivalent if, like one and two, their behaviors are identical. When writing a copy constructor and assignment operator, you attempt to convert an object into a semantically equivalent copy of another object. Consequently, when duplicating certain objects, you are free to pick any copying strategy that creates a semantically-equivalent copy of the source object. In the preceding section, we outlined one possible implementation strategy for a copy constructor and assignment operator that references a function called copyother. While in the case of the DebugVector it was relatively easy to come up with a working copyother implementation, when working with more complicated objects, it can be difficult to devise a working copyother. For example, consider the following class, which encapsulates an unordered linked list:

13 class ListSet public: ListSet(); ListSet(const ListSet &other); ListSet &operator =(const ListSet &other); ~ListSet(); void insert(const T &toadd); bool contains(const T& tofind) const; private: struct cellt T data; cellt *next; ; cellt *list void copyother(const ListSet &other); ; This simple ListSet class exports two simple functions, insert and contains, that insert an element into the list and determine whether the list contains an element. If you'll notice, the add function gives no guarantees about where the element will be inserted, and the contains function ignores ordering, so the lists 0, 1, 2, 3, 4 and the lists 4, 3, 2, 1, 0 are semantically equivalent. Consider two different implementations of copyother: /* Duplicate the list as it exists in the original ListSet. */ void ListSet<T>::copyOther(const ListSet &other) /* Keep track of what the current linked list cell is. */ cellt **current = &list; /* Iterate over the source list. */ for(cellt *source = other.list; source!= NULL; source = source->next) /* Duplicate the cell. */ *current = new cellt; (*current)->data = source->data; (*current)->next = NULL; /* Advance to next element. */ current = &((*current)->next); /* Duplicate list in reverse order of original ListSet */ void ListSet<T>::copyOther(const ListSet &other) for(cellt *source = other.list; source!= NULL; source = source->next) cellt *newnode = new cellt; newnode->data = source->data; newnode->next = list; list = newnode;

14 As you can see, the second version of this function is much, much cleaner than the first. There are no address-of operators floating around, so everything is expressed in terms of simpler pointer operations. But while the second version is cleaner than the first, it duplicates the list in reverse order. Is this a problem? The answer is no. Recall that because we structured the class interface so that ordering doesn't matter, so long as the original object and the duplicate object contain the same elements in some order, they will be semantically equivalent, and from the class interface we would be unable to distinguish the original and source objects. Consider this final version of the copyother function for the ListSet, which duplicates the elements using the ListSet public interface: /* Duplicate list using the add function */ void ListSet<T>::copyOther(const ListSet &other) for(cellt *source = other.list; source!= NULL; source = source->next) add(list->data); This version of copyother is unquestionably the cleanest. If you'll notice, it doesn't matter exactly how add inserts elements into the list (indeed, add could insert the elements at random positions), but we're guaranteed that at the end of the copyother call, the receiving object will be semantically equivalent to the source object. Disabling Copying In CS106B/X we provide you the DISALLOW_COPYING macro, which causes compile-time errors if you try to assign or copy objects of the specified type. DISALLOW_COPYING, however, is not a standard C++ feature. Without using the CS106 library, how can we replicate the functionality? We can't prevent object copying by simply not defining a copy constructor and assignment operator. All this will do is have C++ provide its own default version of these two functions, which is not at all what we want. To solve this problem, provide an assignment operator and copy constructor, but declare them private so that class clients can't access them. For example: class CannotBeCopied public: CannotBeCopied(); /* Other member functions. */ private: CannotBeCopied(const CannotBeCopied &other); CannotBeCopied &operator = (const CannotBeCopied &other); ; Now, if we write code like this: CannotBeCopied one; CannotBeCopied two = one; We'll get a compile-time error on the second line because we're trying to invoke the copy constructor, which has been declared private. We'll get similar behavior when trying to use the assignment operator.

15 Note that when using this trick, you don't need to provide a body for either member function. Since class clients can't invoke the member functions, C++ won't need any code for them. More to Explore While the above method for writing an assignment operator is completely valid, there is another common way to write an assignment operator called copy-and-swap. First, define a swap member function that exchanges the contents of two class instances by swapping all the instance variables (don't have swap make a deep copy, or you'll end up with unreasonably slow copying). Then, have the assignment operator construct a temporary copy of the object to duplicate and then swap the current object and the temporary copy. That way, the copy constructor handles the object duplication, and all the current object's data members will be cleaned up by temporary object's destructor. Practice Problems The only way to learn copy constructors and assignment operators is to play around with them to gain experience. Here are some practice problems and thought questions to get you started: 1. It is syntactically illegal to declare a copy constructor that accepts its parameter by value. For example, given a class MyClass, you cannot declare its copy constructor as MyClass::MyClass(MyClass other). Why not? 2. It is, however, syntactically legal to declare an assignment operator that accepts its parameter by value. Why? 3. In the next handout, we'll see the class CString used as a case study for conversion constructors. CString is simply a class that wraps a C string, storing as data members the char * pointer to the C string and an int length field. Write a copy constructor and assignment operator for CString. 4. Suppose you're implementing the Lexicon class and, for efficiency reasons, you decide to store the words in a sorted vector of C strings (vector<char *>). Assume that the constructor has been provided to you and that it correctly initializes the vector by filling it with strings dynamically allocated from new[]. Write the copy constructor, assignment operator, and destructor for Lexicon. (Hint: When the vector destructor invokes, it will not call delete [] on all of the internally stored char *s, so you will have to do this yourself) 5. If the above Lexicon used a vector<string> instead of a vector<char *>, would you need any of the functions mentioned in the rule of three? 6. What happens if you forget to copy a data member in a copy constructor or assignment operator? 7. Give an example of a class where bitwise equivalence and semantic equivalence are identical. 8. Give an example of a class where bitwise equivalence and semantic equivalence are not identical. (Hint: where are the objects stored in memory?)

Conversion Constructors

Conversion Constructors CS106L Winter 2007-2008 Handout #18 Wednesday, February 27 Conversion Constructors Introduction When designing classes, you might find that certain data types can logically be converted into objects of

More information

CS193D Handout 06 Winter 2004 January 26, 2004 Copy Constructor and operator=

CS193D Handout 06 Winter 2004 January 26, 2004 Copy Constructor and operator= CS193D Handout 06 Winter 2004 January 26, 2004 Copy Constructor and operator= We already know that the compiler will supply a default (zero-argument) constructor if the programmer does not specify one.

More information

Storage Classes CS 110B - Rule Storage Classes Page 18-1 \handouts\storclas

Storage Classes CS 110B - Rule Storage Classes Page 18-1 \handouts\storclas CS 110B - Rule Storage Classes Page 18-1 Attributes are distinctive features of a variable. Data type, int or double for example, is an attribute. Storage class is another attribute. There are four storage

More information

C++FA 5.1 PRACTICE MID-TERM EXAM

C++FA 5.1 PRACTICE MID-TERM EXAM C++FA 5.1 PRACTICE MID-TERM EXAM This practicemid-term exam covers sections C++FA 1.1 through C++FA 1.4 of C++ with Financial Applications by Ben Van Vliet, available at www.benvanvliet.net. 1.) A pointer

More information

Operator Overloading. Lecture 8. Operator Overloading. Running Example: Complex Numbers. Syntax. What can be overloaded. Syntax -- First Example

Operator Overloading. Lecture 8. Operator Overloading. Running Example: Complex Numbers. Syntax. What can be overloaded. Syntax -- First Example Operator Overloading Lecture 8 Operator Overloading C++ feature that allows implementer-defined classes to specify class-specific function for operators Benefits allows classes to provide natural semantics

More information

CS107L Handout 04 Autumn 2007 October 19, 2007 Custom STL-Like Containers and Iterators

CS107L Handout 04 Autumn 2007 October 19, 2007 Custom STL-Like Containers and Iterators CS107L Handout 04 Autumn 2007 October 19, 2007 Custom STL-Like Containers and Iterators This handout is designed to provide a better understanding of how one should write template code and architect iterators

More information

C++ INTERVIEW QUESTIONS

C++ INTERVIEW QUESTIONS C++ INTERVIEW QUESTIONS http://www.tutorialspoint.com/cplusplus/cpp_interview_questions.htm Copyright tutorialspoint.com Dear readers, these C++ Interview Questions have been designed specially to get

More information

IS0020 Program Design and Software Tools Midterm, Feb 24, 2004. Instruction

IS0020 Program Design and Software Tools Midterm, Feb 24, 2004. Instruction IS0020 Program Design and Software Tools Midterm, Feb 24, 2004 Name: Instruction There are two parts in this test. The first part contains 50 questions worth 80 points. The second part constitutes 20 points

More information

Why you shouldn't use set (and what you should use instead) Matt Austern

Why you shouldn't use set (and what you should use instead) Matt Austern Why you shouldn't use set (and what you should use instead) Matt Austern Everything in the standard C++ library is there for a reason, but it isn't always obvious what that reason is. The standard isn't

More information

CS107L Handout 02 Autumn 2007 October 5, 2007 Copy Constructor and operator=

CS107L Handout 02 Autumn 2007 October 5, 2007 Copy Constructor and operator= CS107L Handout 02 Autumn 2007 October 5, 2007 Copy Constructor and operator= Much of the surrounding prose written by Andy Maag, CS193D instructor from years ago. The compiler will supply a default (zero-argument)

More information

Object Oriented Software Design II

Object Oriented Software Design II Object Oriented Software Design II Introduction to C++ Giuseppe Lipari http://retis.sssup.it/~lipari Scuola Superiore Sant Anna Pisa February 20, 2012 G. Lipari (Scuola Superiore Sant Anna) C++ Intro February

More information

C++FA 3.1 OPTIMIZING C++

C++FA 3.1 OPTIMIZING C++ C++FA 3.1 OPTIMIZING C++ Ben Van Vliet Measuring Performance Performance can be measured and judged in different ways execution time, memory usage, error count, ease of use and trade offs usually have

More information

Java Interview Questions and Answers

Java Interview Questions and Answers 1. What is the most important feature of Java? Java is a platform independent language. 2. What do you mean by platform independence? Platform independence means that we can write and compile the java

More information

PART-A Questions. 2. How does an enumerated statement differ from a typedef statement?

PART-A Questions. 2. How does an enumerated statement differ from a typedef statement? 1. Distinguish & and && operators. PART-A Questions 2. How does an enumerated statement differ from a typedef statement? 3. What are the various members of a class? 4. Who can access the protected members

More information

Object Oriented Software Design II

Object Oriented Software Design II Object Oriented Software Design II C++ intro Giuseppe Lipari http://retis.sssup.it/~lipari Scuola Superiore Sant Anna Pisa February 26, 2012 G. Lipari (Scuola Superiore Sant Anna) C++ Intro February 26,

More information

Common Beginner C++ Programming Mistakes

Common Beginner C++ Programming Mistakes Common Beginner C++ Programming Mistakes This documents some common C++ mistakes that beginning programmers make. These errors are two types: Syntax errors these are detected at compile time and you won't

More information

Introduction to Data Structures

Introduction to Data Structures Introduction to Data Structures Albert Gural October 28, 2011 1 Introduction When trying to convert from an algorithm to the actual code, one important aspect to consider is how to store and manipulate

More information

Compile-time type versus run-time type. Consider the parameter to this function:

Compile-time type versus run-time type. Consider the parameter to this function: CS107L Handout 07 Autumn 2007 November 16, 2007 Advanced Inheritance and Virtual Methods Employee.h class Employee public: Employee(const string& name, double attitude, double wage); virtual ~Employee();

More information

A binary search tree or BST is a binary tree that is either empty or in which the data element of each node has a key, and:

A binary search tree or BST is a binary tree that is either empty or in which the data element of each node has a key, and: Binary Search Trees 1 The general binary tree shown in the previous chapter is not terribly useful in practice. The chief use of binary trees is for providing rapid access to data (indexing, if you will)

More information

CpSc212 Goddard Notes Chapter 6. Yet More on Classes. We discuss the problems of comparing, copying, passing, outputting, and destructing

CpSc212 Goddard Notes Chapter 6. Yet More on Classes. We discuss the problems of comparing, copying, passing, outputting, and destructing CpSc212 Goddard Notes Chapter 6 Yet More on Classes We discuss the problems of comparing, copying, passing, outputting, and destructing objects. 6.1 Object Storage, Allocation and Destructors Some objects

More information

Name: Class: Date: 9. The compiler ignores all comments they are there strictly for the convenience of anyone reading the program.

Name: Class: Date: 9. The compiler ignores all comments they are there strictly for the convenience of anyone reading the program. Name: Class: Date: Exam #1 - Prep True/False Indicate whether the statement is true or false. 1. Programming is the process of writing a computer program in a language that the computer can respond to

More information

Object-Oriented Design Lecture 4 CSU 370 Fall 2007 (Pucella) Tuesday, Sep 18, 2007

Object-Oriented Design Lecture 4 CSU 370 Fall 2007 (Pucella) Tuesday, Sep 18, 2007 Object-Oriented Design Lecture 4 CSU 370 Fall 2007 (Pucella) Tuesday, Sep 18, 2007 The Java Type System By now, you have seen a fair amount of Java. Time to study in more depth the foundations of the language,

More information

1 Abstract Data Types Information Hiding

1 Abstract Data Types Information Hiding 1 1 Abstract Data Types Information Hiding 1.1 Data Types Data types are an integral part of every programming language. ANSI-C has int, double and char to name just a few. Programmers are rarely content

More information

Semantic Analysis: Types and Type Checking

Semantic Analysis: Types and Type Checking Semantic Analysis Semantic Analysis: Types and Type Checking CS 471 October 10, 2007 Source code Lexical Analysis tokens Syntactic Analysis AST Semantic Analysis AST Intermediate Code Gen lexical errors

More information

Data Structures Using C++ 2E. Chapter 5 Linked Lists

Data Structures Using C++ 2E. Chapter 5 Linked Lists Data Structures Using C++ 2E Chapter 5 Linked Lists Test #1 Next Thursday During Class Cover through (near?) end of Chapter 5 Objectives Learn about linked lists Become aware of the basic properties of

More information

PROBLEM SOLVING SEVENTH EDITION WALTER SAVITCH UNIVERSITY OF CALIFORNIA, SAN DIEGO CONTRIBUTOR KENRICK MOCK UNIVERSITY OF ALASKA, ANCHORAGE PEARSON

PROBLEM SOLVING SEVENTH EDITION WALTER SAVITCH UNIVERSITY OF CALIFORNIA, SAN DIEGO CONTRIBUTOR KENRICK MOCK UNIVERSITY OF ALASKA, ANCHORAGE PEARSON PROBLEM SOLVING WITH SEVENTH EDITION WALTER SAVITCH UNIVERSITY OF CALIFORNIA, SAN DIEGO CONTRIBUTOR KENRICK MOCK UNIVERSITY OF ALASKA, ANCHORAGE PEARSON Addison Wesley Boston San Francisco New York London

More information

Common Data Structures

Common Data Structures Data Structures 1 Common Data Structures Arrays (single and multiple dimensional) Linked Lists Stacks Queues Trees Graphs You should already be familiar with arrays, so they will not be discussed. Trees

More information

The C Programming Language course syllabus associate level

The C Programming Language course syllabus associate level TECHNOLOGIES The C Programming Language course syllabus associate level Course description The course fully covers the basics of programming in the C programming language and demonstrates fundamental programming

More information

Variable Base Interface

Variable Base Interface Chapter 6 Variable Base Interface 6.1 Introduction Finite element codes has been changed a lot during the evolution of the Finite Element Method, In its early times, finite element applications were developed

More information

C++ Overloading, Constructors, Assignment operator

C++ Overloading, Constructors, Assignment operator C++ Overloading, Constructors, Assignment operator 1 Overloading Before looking at the initialization of objects in C++ with constructors, we need to understand what function overloading is In C, two functions

More information

Goals for This Lecture:

Goals for This Lecture: Goals for This Lecture: Understand the pass-by-value and passby-reference argument passing mechanisms of C++ Understand the use of C++ arrays Understand how arrays are passed to C++ functions Call-by-value

More information

N3458: Simple Database Integration in C++11

N3458: Simple Database Integration in C++11 N3458: Simple Database Integration in C++11 Thomas Neumann Technische Univeristät München neumann@in.tum.de 2012-10-22 Many applications make use of relational database to store and query their data. However,

More information

Software Engineering Concepts: Testing. Pointers & Dynamic Allocation. CS 311 Data Structures and Algorithms Lecture Slides Monday, September 14, 2009

Software Engineering Concepts: Testing. Pointers & Dynamic Allocation. CS 311 Data Structures and Algorithms Lecture Slides Monday, September 14, 2009 Software Engineering Concepts: Testing Simple Class Example continued Pointers & Dynamic Allocation CS 311 Data Structures and Algorithms Lecture Slides Monday, September 14, 2009 Glenn G. Chappell Department

More information

In order to understand Perl objects, you first need to understand references in Perl. See perlref for details.

In order to understand Perl objects, you first need to understand references in Perl. See perlref for details. NAME DESCRIPTION perlobj - Perl object reference This document provides a reference for Perl's object orientation features. If you're looking for an introduction to object-oriented programming in Perl,

More information

Comp151. Definitions & Declarations

Comp151. Definitions & Declarations Comp151 Definitions & Declarations Example: Definition /* reverse_printcpp */ #include #include using namespace std; int global_var = 23; // global variable definition void reverse_print(const

More information

Symbol Tables. Introduction

Symbol Tables. Introduction Symbol Tables Introduction A compiler needs to collect and use information about the names appearing in the source program. This information is entered into a data structure called a symbol table. The

More information

13 Classes & Objects with Constructors/Destructors

13 Classes & Objects with Constructors/Destructors 13 Classes & Objects with Constructors/Destructors 13.1 Introduction In object oriented programming, the emphasis is on data rather than function. Class is a way that binds the data & function together.

More information

Organization of Programming Languages CS320/520N. Lecture 05. Razvan C. Bunescu School of Electrical Engineering and Computer Science bunescu@ohio.

Organization of Programming Languages CS320/520N. Lecture 05. Razvan C. Bunescu School of Electrical Engineering and Computer Science bunescu@ohio. Organization of Programming Languages CS320/520N Razvan C. Bunescu School of Electrical Engineering and Computer Science bunescu@ohio.edu Names, Bindings, and Scopes A name is a symbolic identifier used

More information

CORBA Programming with TAOX11. The C++11 CORBA Implementation

CORBA Programming with TAOX11. The C++11 CORBA Implementation CORBA Programming with TAOX11 The C++11 CORBA Implementation TAOX11: the CORBA Implementation by Remedy IT TAOX11 simplifies development of CORBA based applications IDL to C++11 language mapping is easy

More information

Lab Experience 17. Programming Language Translation

Lab Experience 17. Programming Language Translation Lab Experience 17 Programming Language Translation Objectives Gain insight into the translation process for converting one virtual machine to another See the process by which an assembler translates assembly

More information

1. Polymorphism in C++...2

1. Polymorphism in C++...2 1. Polymorphism in C++...2 1.1 Polymorphism and virtual functions... 2 1.2 Function call binding... 3 1.3 Virtual functions... 4 1.4 How C++ implements late binding... 6 1.4.1 Why do I have to know at

More information

Lecture 11 Doubly Linked Lists & Array of Linked Lists. Doubly Linked Lists

Lecture 11 Doubly Linked Lists & Array of Linked Lists. Doubly Linked Lists Lecture 11 Doubly Linked Lists & Array of Linked Lists In this lecture Doubly linked lists Array of Linked Lists Creating an Array of Linked Lists Representing a Sparse Matrix Defining a Node for a Sparse

More information

Chapter 10: Operator Overloading

Chapter 10: Operator Overloading Consider the following C++ code snippet: vector myvector(knumstrings); for(vector::iterator itr = myvector.begin(); itr!= myvector.end(); ++itr) *itr += "Now longer!"; Here, we create a

More information

Glossary of Object Oriented Terms

Glossary of Object Oriented Terms Appendix E Glossary of Object Oriented Terms abstract class: A class primarily intended to define an instance, but can not be instantiated without additional methods. abstract data type: An abstraction

More information

KITES TECHNOLOGY COURSE MODULE (C, C++, DS)

KITES TECHNOLOGY COURSE MODULE (C, C++, DS) KITES TECHNOLOGY 360 Degree Solution www.kitestechnology.com/academy.php info@kitestechnology.com technologykites@gmail.com Contact: - 8961334776 9433759247 9830639522.NET JAVA WEB DESIGN PHP SQL, PL/SQL

More information

Object Oriented Software Design II

Object Oriented Software Design II Object Oriented Software Design II Real Application Design Christian Nastasi http://retis.sssup.it/~lipari http://retis.sssup.it/~chris/cpp Scuola Superiore Sant Anna Pisa April 25, 2012 C. Nastasi (Scuola

More information

Not agree with bug 3, precision actually was. 8,5 not set in the code. Not agree with bug 3, precision actually was

Not agree with bug 3, precision actually was. 8,5 not set in the code. Not agree with bug 3, precision actually was Task 1 Task 2 Task 3 Feedback Presence SUM Matrikkel Rühm [5] [1] [2] [1] [1] [10] Feedback to students A64129 1. rühm 0 0 No submission found A72068 1. rühm 5 1 2 1 1 For Bug 3. Actually the variable

More information

CS104: Data Structures and Object-Oriented Design (Fall 2013) October 24, 2013: Priority Queues Scribes: CS 104 Teaching Team

CS104: Data Structures and Object-Oriented Design (Fall 2013) October 24, 2013: Priority Queues Scribes: CS 104 Teaching Team CS104: Data Structures and Object-Oriented Design (Fall 2013) October 24, 2013: Priority Queues Scribes: CS 104 Teaching Team Lecture Summary In this lecture, we learned about the ADT Priority Queue. A

More information

CHAPTER 4 ESSENTIAL DATA STRUCTRURES

CHAPTER 4 ESSENTIAL DATA STRUCTRURES CHAPTER 4 ESSENTIAL DATA STRUCTURES 72 CHAPTER 4 ESSENTIAL DATA STRUCTRURES In every algorithm, there is a need to store data. Ranging from storing a single value in a single variable, to more complex

More information

Database Programming with PL/SQL: Learning Objectives

Database Programming with PL/SQL: Learning Objectives Database Programming with PL/SQL: Learning Objectives This course covers PL/SQL, a procedural language extension to SQL. Through an innovative project-based approach, students learn procedural logic constructs

More information

Copyright 2001, Bill Trudell. Permission is granted to copy for the PLoP 2001 conference. All other rights reserved.

Copyright 2001, Bill Trudell. Permission is granted to copy for the PLoP 2001 conference. All other rights reserved. The Secret Partner Pattern Revision 3a by Bill Trudell, July 23, 2001 Submitted to the Pattern Languages of Programs Shepherd: Neil Harrison PC Member: Kyle Brown Thumbnail This paper describes the Secret

More information

Classes and Pointers: Some Peculiarities (cont d.)

Classes and Pointers: Some Peculiarities (cont d.) Classes and Pointers: Some Peculiarities (cont d.) Assignment operator Built-in assignment operators for classes with pointer member variables may lead to shallow copying of data FIGURE 3-22 Objects objectone

More information

UIL Computer Science for Dummies by Jake Warren and works from Mr. Fleming

UIL Computer Science for Dummies by Jake Warren and works from Mr. Fleming UIL Computer Science for Dummies by Jake Warren and works from Mr. Fleming 1 2 Foreword First of all, this book isn t really for dummies. I wrote it for myself and other kids who are on the team. Everything

More information

El Dorado Union High School District Educational Services

El Dorado Union High School District Educational Services El Dorado Union High School District Course of Study Information Page Course Title: ACE Computer Programming II (#495) Rationale: A continuum of courses, including advanced classes in technology is needed.

More information

6.088 Intro to C/C++ Day 4: Object-oriented programming in C++ Eunsuk Kang and Jean Yang

6.088 Intro to C/C++ Day 4: Object-oriented programming in C++ Eunsuk Kang and Jean Yang 6.088 Intro to C/C++ Day 4: Object-oriented programming in C++ Eunsuk Kang and Jean Yang Today s topics Why objects? Object-oriented programming (OOP) in C++ classes fields & methods objects representation

More information

Formal Languages and Automata Theory - Regular Expressions and Finite Automata -

Formal Languages and Automata Theory - Regular Expressions and Finite Automata - Formal Languages and Automata Theory - Regular Expressions and Finite Automata - Samarjit Chakraborty Computer Engineering and Networks Laboratory Swiss Federal Institute of Technology (ETH) Zürich March

More information

Section 15 Revision Techniques

Section 15 Revision Techniques Section 15 Revision Techniques Introduction This section in your Study Skills manual will consolidate information relating to revision techniques. This section will consider how to prepare for examinations

More information

arrays C Programming Language - Arrays

arrays C Programming Language - Arrays arrays So far, we have been using only scalar variables scalar meaning a variable with a single value But many things require a set of related values coordinates or vectors require 3 (or 2, or 4, or more)

More information

1. The memory address of the first element of an array is called A. floor address B. foundation addressc. first address D.

1. The memory address of the first element of an array is called A. floor address B. foundation addressc. first address D. 1. The memory address of the first element of an array is called A. floor address B. foundation addressc. first address D. base address 2. The memory address of fifth element of an array can be calculated

More information

Free Java textbook available online. Introduction to the Java programming language. Compilation. A simple java program

Free Java textbook available online. Introduction to the Java programming language. Compilation. A simple java program Free Java textbook available online "Thinking in Java" by Bruce Eckel, 4th edition, 2006, ISBN 0131872486, Pearson Education Introduction to the Java programming language CS 4354 Summer II 2015 The third

More information

C++ Programming Language

C++ Programming Language C++ Programming Language Lecturer: Yuri Nefedov 7th and 8th semesters Lectures: 34 hours (7th semester); 32 hours (8th semester). Seminars: 34 hours (7th semester); 32 hours (8th semester). Course abstract

More information

Description of Class Mutation Mutation Operators for Java

Description of Class Mutation Mutation Operators for Java Description of Class Mutation Mutation Operators for Java Yu-Seung Ma Electronics and Telecommunications Research Institute, Korea ysma@etri.re.kr Jeff Offutt Software Engineering George Mason University

More information

Classes and Objects in Java Constructors. In creating objects of the type Fraction, we have used statements similar to the following:

Classes and Objects in Java Constructors. In creating objects of the type Fraction, we have used statements similar to the following: In creating objects of the type, we have used statements similar to the following: f = new (); The parentheses in the expression () makes it look like a method, yet we never created such a method in our

More information

Node-Based Structures Linked Lists: Implementation

Node-Based Structures Linked Lists: Implementation Linked Lists: Implementation CS 311 Data Structures and Algorithms Lecture Slides Monday, March 30, 2009 Glenn G. Chappell Department of Computer Science University of Alaska Fairbanks CHAPPELLG@member.ams.org

More information

An Incomplete C++ Primer. University of Wyoming MA 5310

An Incomplete C++ Primer. University of Wyoming MA 5310 An Incomplete C++ Primer University of Wyoming MA 5310 Professor Craig C. Douglas http://www.mgnet.org/~douglas/classes/na-sc/notes/c++primer.pdf C++ is a legacy programming language, as is other languages

More information

1 Description of The Simpletron

1 Description of The Simpletron Simulating The Simpletron Computer 50 points 1 Description of The Simpletron In this assignment you will write a program to simulate a fictional computer that we will call the Simpletron. As its name implies

More information

C++ Crash Kurs. C++ Object-Oriented Programming

C++ Crash Kurs. C++ Object-Oriented Programming C++ Crash Kurs C++ Object-Oriented Programming Dr. Dennis Pfisterer Institut für Telematik, Universität zu Lübeck http://www.itm.uni-luebeck.de/people/pfisterer C++ classes A class is user-defined type

More information

Boolean Expressions, Conditions, Loops, and Enumerations. Precedence Rules (from highest to lowest priority)

Boolean Expressions, Conditions, Loops, and Enumerations. Precedence Rules (from highest to lowest priority) Boolean Expressions, Conditions, Loops, and Enumerations Relational Operators == // true if two values are equivalent!= // true if two values are not equivalent < // true if left value is less than the

More information

Creating and Using Master Documents

Creating and Using Master Documents Creating and Using Master Documents Title: Creating and Using Master Documents Version: 0.3 First edition: 09/04 Contents Overview...2 Acknowledgments...2 Modifications and updates... 2 Why use a master

More information

Chapter 5 Names, Bindings, Type Checking, and Scopes

Chapter 5 Names, Bindings, Type Checking, and Scopes Chapter 5 Names, Bindings, Type Checking, and Scopes Chapter 5 Topics Introduction Names Variables The Concept of Binding Type Checking Strong Typing Scope Scope and Lifetime Referencing Environments Named

More information

Moving from CS 61A Scheme to CS 61B Java

Moving from CS 61A Scheme to CS 61B Java Moving from CS 61A Scheme to CS 61B Java Introduction Java is an object-oriented language. This document describes some of the differences between object-oriented programming in Scheme (which we hope you

More information

Introduction to C++ Introduction to C++ Week 7 Dr Alex Martin 2013 Slide 1

Introduction to C++ Introduction to C++ Week 7 Dr Alex Martin 2013 Slide 1 Introduction to C++ Introduction to C++ Week 7 Dr Alex Martin 2013 Slide 1 Introduction to Classes Classes as user-defined types We have seen that C++ provides a fairly large set of built-in types. e.g

More information

Microsoft Excel Tips & Tricks

Microsoft Excel Tips & Tricks Microsoft Excel Tips & Tricks Collaborative Programs Research & Evaluation TABLE OF CONTENTS Introduction page 2 Useful Functions page 2 Getting Started with Formulas page 2 Nested Formulas page 3 Copying

More information

CISC 181 Project 3 Designing Classes for Bank Accounts

CISC 181 Project 3 Designing Classes for Bank Accounts CISC 181 Project 3 Designing Classes for Bank Accounts Code Due: On or before 12 Midnight, Monday, Dec 8; hardcopy due at beginning of lecture, Tues, Dec 9 What You Need to Know This project is based on

More information

1.1.3 Syntax The syntax for creating a derived class is very simple. (You will wish everything else about it were so simple though.

1.1.3 Syntax The syntax for creating a derived class is very simple. (You will wish everything else about it were so simple though. Stewart Weiss Inheritance is a feature that is present in many object-oriented languages such as C++, Eiffel, Java, Ruby, and Smalltalk, but each language implements it in its own way. This chapter explains

More information

Building Dynamic Websites With the MVC Pattern. ACM Webmonkeys @ UIUC, 2010

Building Dynamic Websites With the MVC Pattern. ACM Webmonkeys @ UIUC, 2010 Building Dynamic Websites With the MVC Pattern ACM Webmonkeys @ UIUC, 2010 Recap A dynamic website is a website which uses some serverside language to generate HTML pages PHP is a common and ubiquitous

More information

Free Java textbook available online. Introduction to the Java programming language. Compilation. A simple java program

Free Java textbook available online. Introduction to the Java programming language. Compilation. A simple java program Free Java textbook available online "Thinking in Java" by Bruce Eckel, 4th edition, 2006, ISBN 0131872486, Pearson Education Introduction to the Java programming language CS 4354 Summer II 2014 Jill Seaman

More information

For the next three questions, consider the class declaration: Member function implementations put inline to save space.

For the next three questions, consider the class declaration: Member function implementations put inline to save space. Instructions: This homework assignment focuses on basic facts regarding classes in C++. Submit your answers via the Curator System as OQ4. For the next three questions, consider the class declaration:

More information

Introduction to Objective-C. Kevin Cathey

Introduction to Objective-C. Kevin Cathey Introduction to Objective-C Kevin Cathey Introduction to Objective-C What are object-oriented systems? What is the Objective-C language? What are objects? How do you create classes in Objective-C? acm.uiuc.edu/macwarriors/devphone

More information

Object Oriented Software Design

Object Oriented Software Design Object Oriented Software Design Introduction to Java - II Giuseppe Lipari http://retis.sssup.it/~lipari Scuola Superiore Sant Anna Pisa September 14, 2011 G. Lipari (Scuola Superiore Sant Anna) Introduction

More information

Handout 1. Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner.

Handout 1. Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner. Handout 1 CS603 Object-Oriented Programming Fall 15 Page 1 of 11 Handout 1 Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner. Java

More information

Binary storage of graphs and related data

Binary storage of graphs and related data EÖTVÖS LORÁND UNIVERSITY Faculty of Informatics Department of Algorithms and their Applications Binary storage of graphs and related data BSc thesis Author: Frantisek Csajka full-time student Informatics

More information

CSCI 253. Object Oriented Programming (OOP) Overview. George Blankenship 1. Object Oriented Design: Java Review OOP George Blankenship.

CSCI 253. Object Oriented Programming (OOP) Overview. George Blankenship 1. Object Oriented Design: Java Review OOP George Blankenship. CSCI 253 Object Oriented Design: Java Review OOP George Blankenship George Blankenship 1 Object Oriented Programming (OOP) OO Principles Abstraction Encapsulation Abstract Data Type (ADT) Implementation

More information

Basic Object-Oriented Programming in Java

Basic Object-Oriented Programming in Java core programming Basic Object-Oriented Programming in Java 1 2001-2003 Marty Hall, Larry Brown http:// Agenda Similarities and differences between Java and C++ Object-oriented nomenclature and conventions

More information

17. Friendship and Inheritance

17. Friendship and Inheritance - 117 - Object Oriented Programming: 17. Friendship and Inheritance Friend functions In principle, private and protected members of a class cannot be accessed from outside the same class in which they

More information

ECON 459 Game Theory. Lecture Notes Auctions. Luca Anderlini Spring 2015

ECON 459 Game Theory. Lecture Notes Auctions. Luca Anderlini Spring 2015 ECON 459 Game Theory Lecture Notes Auctions Luca Anderlini Spring 2015 These notes have been used before. If you can still spot any errors or have any suggestions for improvement, please let me know. 1

More information

Object-Oriented Programming

Object-Oriented Programming Object-Oriented Programming Programming with Data Types to enhance reliability and productivity (through reuse and by facilitating evolution) Object (instance) State (fields) Behavior (methods) Identity

More information

if and if-else: Part 1

if and if-else: Part 1 if and if-else: Part 1 Objectives Write if statements (including blocks) Write if-else statements (including blocks) Write nested if-else statements We will now talk about writing statements that make

More information

Multichoice Quetions 1. Atributes a. are listed in the second part of the class box b. its time is preceded by a colon. c. its default value is

Multichoice Quetions 1. Atributes a. are listed in the second part of the class box b. its time is preceded by a colon. c. its default value is Multichoice Quetions 1. Atributes a. are listed in the second part of the class box b. its time is preceded by a colon. c. its default value is preceded by an equal sign d. its name has undereline 2. Associations

More information

Polymorphism. Problems with switch statement. Solution - use virtual functions (polymorphism) Polymorphism

Polymorphism. Problems with switch statement. Solution - use virtual functions (polymorphism) Polymorphism Polymorphism Problems with switch statement Programmer may forget to test all possible cases in a switch. Tracking this down can be time consuming and error prone Solution - use virtual functions (polymorphism)

More information

Basic Programming and PC Skills: Basic Programming and PC Skills:

Basic Programming and PC Skills: Basic Programming and PC Skills: Texas University Interscholastic League Contest Event: Computer Science The contest challenges high school students to gain an understanding of the significance of computation as well as the details of

More information

Designing with Exceptions. CSE219, Computer Science III Stony Brook University http://www.cs.stonybrook.edu/~cse219

Designing with Exceptions. CSE219, Computer Science III Stony Brook University http://www.cs.stonybrook.edu/~cse219 Designing with Exceptions CSE219, Computer Science III Stony Brook University http://www.cs.stonybrook.edu/~cse219 Testing vs. Debugging Testing Coding Does the code work properly YES NO 2 Debugging Testing

More information

Sources: On the Web: Slides will be available on:

Sources: On the Web: Slides will be available on: C programming Introduction The basics of algorithms Structure of a C code, compilation step Constant, variable type, variable scope Expression and operators: assignment, arithmetic operators, comparison,

More information

Formatting Numbers with C++ Output Streams

Formatting Numbers with C++ Output Streams Formatting Numbers with C++ Output Streams David Kieras, EECS Dept., Univ. of Michigan Revised for EECS 381, Winter 2004. Using the output operator with C++ streams is generally easy as pie, with the only

More information

CS193j, Stanford Handout #10 OOP 3

CS193j, Stanford Handout #10 OOP 3 CS193j, Stanford Handout #10 Summer, 2003 Manu Kumar OOP 3 Abstract Superclass Factor Common Code Up Several related classes with overlapping code Factor common code up into a common superclass Examples

More information

1.2 Using the GPG Gen key Command

1.2 Using the GPG Gen key Command Creating Your Personal Key Pair GPG uses public key cryptography for encrypting and signing messages. Public key cryptography involves your public key which is distributed to the public and is used to

More information

1 bool operator==(complex a, Complex b) { 2 return a.real()==b.real() 3 && a.imag()==b.imag(); 4 } 1 bool Complex::operator==(Complex b) {

1 bool operator==(complex a, Complex b) { 2 return a.real()==b.real() 3 && a.imag()==b.imag(); 4 } 1 bool Complex::operator==(Complex b) { Operators C and C++ 6. Operators Inheritance Virtual Alastair R. Beresford University of Cambridge Lent Term 2008 C++ allows the programmer to overload the built-in operators For example, a new test for

More information

What is a Loop? Pretest Loops in C++ Types of Loop Testing. Count-controlled loops. Loops can be...

What is a Loop? Pretest Loops in C++ Types of Loop Testing. Count-controlled loops. Loops can be... What is a Loop? CSC Intermediate Programming Looping A loop is a repetition control structure It causes a single statement or a group of statements to be executed repeatedly It uses a condition to control

More information

Stack Allocation. Run-Time Data Structures. Static Structures

Stack Allocation. Run-Time Data Structures. Static Structures Run-Time Data Structures Stack Allocation Static Structures For static structures, a fixed address is used throughout execution. This is the oldest and simplest memory organization. In current compilers,

More information

Lecture Notes on Binary Search Trees

Lecture Notes on Binary Search Trees Lecture Notes on Binary Search Trees 15-122: Principles of Imperative Computation Frank Pfenning André Platzer Lecture 17 October 23, 2014 1 Introduction In this lecture, we will continue considering associative

More information