ADDS exam summary PDF

Title ADDS exam summary
Course Algorithm Design & Data Structures
Institution The University of Adelaide
Pages 66
File Size 3.1 MB
File Type PDF
Total Downloads 71
Total Views 175

Summary

LECTURE 2 | 31ST JULYReview: pointersReview of pointers What are pointer variables? - A pointer variable is a variable pointing to the memory address of another variable. It gives us more control on the computer’s memory.  How do we create them? - You can create a pointer variable by using the * ...


Description

LECTURE 2 | 31ST JULY Review: pointers Review of pointers 





What are pointer variables? - A pointer variable is a variable pointing to the memory address of another variable. It gives us more control on the computer’s memory. How do we create them? - You can create a pointer variable by using the *

How do we use them in C++? - You can refer to the address of a variable using &

V = 100 Why pointers/references? 

 

Instead of passing large quantities of data between functions, we can - Just pass the pointer to the start of the data. - Saves memory and data transfer. Dynamic memory usage. Pass parameters to a function by reference.

Dynamic Variables 

 

What are dynamic variables? - Variables that are created by using new operator. - They are created and destroyed while the program is running. “new” allocates a part of memory as the dynamic variable. We need to “delete” dynamic variables after use, to prevent memory leak - Type *ptr = new type; - Set a value to *ptr and use it - When you no longer need it: Delete ptr;



The C++ standard specifies that if there is no sufficient memory available to create the new variable -> the new operator, by default, terminates the program.

Where are the variables stored?    

Static variables and parameters are stored in Stack. The rest of the allocated memory is used as the heap; for dynamic memory allocation. The stack and heap are in a shared area. The memory that is allocated to variables and parameters from stack is not released until their function is returned. Unlike memory allocation in Heap.

Pointer Arithmetic 

 

You cannot perform the normal arithmetic operations on pointers. - Multiplication or division is not allowed - Addition and subtraction are different The pointer arithmetic depends on the size of the type that pointer is of that type. Pointer arithmetic (+/-) shifts the address by a number of bytes equal to the size of the pointer type

Pointers and Arrays 

In C++, an array variable is actually a pointer variable that points to the first indexed variable of the array.

LECTURE 3 | 2ND AUGUST Review: memory Variables in C++ 

Three variables: Global, Automatic and Dynamic.

Global Variables   

Global variables are declared outside of any function definition. When main starts executing, these variables are already defined! They exist as long as the program is running. Hard to manage safely (avoid unless necessary)

Automatic Variables 

Automatic variables are created for you to use, automatically, whenever a function is called. o Local to a function or the main part of the program. o Once the function is returned, the variables are destroyed.

Dynamic Variables 

Dynamic variables are created and destroyed as the program Is running. o These variables are created with new and destroyed with delete. o No automatic deletion during runtime! o Used primarily when we don’t know if needed or size until program runs.

Where are they stored? Stack, Heap and Data   

Globals are stored in Data area. o Lifetime of process. Automatic are stored on Stack. o Lifetime of function. Dynamic are stored in Heap o Lifetime until delete is called on them or program exits.

The Heap  

An area reserved for dynamic variables. It is also called the freestore. Two drawbacks: Searching, Heap fragmentation.

The Stack  

Last In First Out. For allocating memory to some new variable, we just need to keep track of where the free block starts.

Answer to quiz: All four of them! Stack and Heap – limits 



The stack keeps track of all of the variables and parameters that you are currently using – also called an activation record. o Call too many functions – run out of stack! (stack overflow) The heap, or freestore, allows you to create dynamic variables and refer to them with pointers, with the new command. Use delete to hand it back. o Use too much of it and calls to new will fail!

Memory management  



Automatic variables will have their memory returned to the stack by the compiler. Dynamic variables are the programmer’s responsibility. o new without delete will continue to use more and more memory. o Losing track of memory is referred to as a memory leak – eventually, something’s going to happen. o In order to prevent memory leak, delete the memory of a pointer whenever you want to set it to another part of the memory by new. Returning memory to the freestore doesn’t solve all of our memory challenges.

Segmentation Faults 

 

Your program will crash if you try to: o Use memory that isn’t allocated to you:  Use a deleted variable  Use uninitialized objects;  Go outside arrays o Try to write to memory that’s read only. o Use up all the memory. In some cases, this crash will also leave a copy of the computer’s memory state – referred to as a core dump. Runtime problems cause segmentation faults and crash. Core dumps help you with finding the problem.

Debugging Segmentation Fault   

Try to avoid this by taking care of the memory management by following a good programming style. Compile your code with -g option and use gdb to get stacktrace of the segmentation fault. “cout” what you expect for Debugging.

Dynamic Array 

It is illegal/meaningless to change the pointer value in an array variable.



For ordinary arrays you must specify the size of the array when you write the program. A dynamic array is an array whose size is not specified when you write the program, but is determined while the program is running.



Dynamic Arrays 

Dynamic arrays are created using the new operator.

  

Dynamic arrays are used like ordinary arrays. Remember to call delete[ ] when your program is finished with the dynamic arrays. Delete dArray; - Undefined behaviour.

Multi-Dimensional Array 

Two-Dimensional Array



An object of array type contains a contiguously allocated non-empty set of N subobjects of type T.



Pointer to Pointer (multiple indirection) o Where is a stored? How about pointers to rows? o How about the rows?



In C++ you can create n-dimensional arrays for any integer n.

Passing Arrays to Functions  

Pass-by-value Pass-by-reference

Returning Arrays from Functions  

It is not allowed in C++ Two options: o Passing another array argument in the function. o Return a pointer  Not a good idea to return the address of a local variable!!  But OK if we are creating a new array to return dynamically

Pointer to Functions

Answer to quiz: A and C!

LECTURE 4 | 5TH AUGUST Abstract Data Types Data Type  

Types are more than just values, they also come with a valid set of operations. A data type is the values AND the set of operations defined over these values.

Abstract Data Types   

Suppose we have a type where the public member functions provide a large number of increasingly more complex operations. Now, think about that we can do something with the type, but have no idea how it is doing it – or change how it is being done. The details have been abstracted away from us. o A data type is called an ADT is the programmers who use the type have no access to the details of the implementation.

Not all classes are ADTs   

Programmer-defined types are not automatically ADTs. Unless defined and used with care, the programmer-defined types can make a program difficult to understand and modify. We need to control access to make sure that only part of the behaviour is available to others.

Separation   

We need to separate the specification of how the type is used by the users from the details of how the type is implemented. Class abstraction is the separation of class implementation from the use of a class. Rules: o Make all member variables private. o Make the basic operations public and specify how to use them. o Make any helping functions private.

Interfaces  

The set of public member functions in our class, along with a description of what they do, make up the interface of the ADT. This should be all that someone needs to know to use your ADT.

Implementation 

The implementation of the ADT tells how this interface is realized as C++ code, including: o Definitions of public functions. o Any private or public variables. o Any private ‘helper’ functions.

ADTs and Black Boxes    

From a design point of view, the implementation of an ADT is like a Black Box – you can’t see inside it. All a programmer can see is your interface. A programmer shouldn’t NEED to know about the implementation to make the ADT work. This is also known as information hiding.

More Complex Data Structures  

Another really good application of ADTs is in controlling access to more complex data structures. Vector? Vector provides bound checking on the at() function.

The Circular Array 

As we keep inserting elements, we “wrap around” to the beginning of the array.

LECTURE 5 | 7TH AUGUST Class Hierarchies

Design 

Design a software such that it: o Solves the problem correctly. o Does so efficiently. o Is easy to maintain. o Is potentially applicable to other areas.

Classes    

A class is a template or a blueprint that defines what an object’s data and functions will be. Objects will call methods on each other. The methods should be strongly associated with the data of that class. Practice and experience -> Good design. o Distinct groupings of variables o Split the desired behaviour.

Splitting the behaviour 

Make sure that the separation: o Makes sense o Efficient

Example 



Consider a class of vehicles. There are many common features that all vehicles have. o Variables include: carrying capacity, number of passengers. o Methods include: add passenger, move vehicle. However, there are also some features that only belong to a certain type of vehicles.

Why hierarchies? 

 

We could write separate classes: Vehicle class, Car class, Bike class, Aircraft class. o Similar properties o Vast duplication of code o Hard to maintain Why not take a different approach and build classes out of OTHER classes? The class hierarchy defines the inheritance relationship between the classes.

Example



 

Consider the Vehicle class o Subclass Cars o Subclass Bikes. What are the differences between a car and a bike? How do we model these in terms of: o Variables (data)? o Methods (behaviours)?

Class Hierarchies 

  

One key problem in constructing a class hierarchy: o Focus on the relationships between the concepts (common sense) instead of considering the behaviours and how we should implement them. Is a Car a separate class near the top or is it just a vehicle with an engine with four wheels? Are we adding a behaviour or changing a default? We should design the class hierarchy based on our requirements.

Class Hierarchies 



The class hierarchies that you should form as a part of your design must: o Solve the problem in hand o Be efficient o Reduce code duplication o Be well-defined and clearly understood Class hierarchies allow us to build new classes derived from existing classes. o Get it right once, then we can re-use it. o But how do we re-use it?

Inheritance      

Inheritance in Object-oriented programming: Derive new classes from existing classes. Class A extended from class B. Class A: derived class or child class. Class B: base class or parent class A derived class and its base class must have the is-a relationship. We usually assume that: o A derived class has extra features o We derive our class from the most appropriate original class

Example 



Why do we have Birds, then Eagles and Parrots? o Animals have heart rates, geographical location and food type. o Birds have wing spans, feather type and egg colours. o Parrots: A rank for their talking ability o Birds are Animals. o Parrots are birds. Every Bird is an Animal but not every Animal is a Bird!

Family relationships   

The derived class Bird is a subclass/child class of Animal. Animal is a parent class of Bird. Bird inherits the member functions of Animal.

Child Class 





The child class inherits from the parent: o All public member variables o All public member functions We can add member functions and variables to the child. o Are these available to the parent? No! o Are available to children of the child? Yes We can also redefine (avoid)/override (using virtual) the member functions of the parent as viewed by the child.

Advantages 



Update easily o If the child classes inherit methods from the parent and then we change the parent, all children automatically get access to the new, improved code. Very, very powerful technique o We can use the child In places where we could use the parent, although we are restricted to the methods publicly available from the parent.

Example

  

The constructors of a base class are not automatically inherited in the derived class. One constructor of the base class must be invoked to initialise the variables in the base class If you don’t name it, the constructor with no argument will be automatically invoked.

LECTURE 6 | 9TH AUGUST Inheritance and Friends Access Specifiers    

Private members can only be accessed from the inside of the class. (default for objects) Public members can be accessed from any other classes. A protected member (data field or function) in a base class can be accessed in its derived classes. While, technically, we inherit almost everything from a parent, we cant USE everything from the parent, unless its set up correctly.

Access Specifier on Inheritance 

Things that we inherit and use from a parent, are not necessarily visible from outside our class.

Types of Inheritance 

 

With public inheritance o Public members of parent become public members of child o Protected members of base become protected members of child With protected inheritance o Public and protected members of parent become protected members of child With private inheritance o Public and protected members of parent become private members of child

Inheritance: some points 

Regardless of access specifier: o The derived class inherits access to all public and protected members from the base class o The derived class has no access to the private members of the base class o The constructors and destructors of the base class are not members and therefore are not inherited o The assignment operator, while inherited, is hidden and can not be accessed. o The friend functions and classes of the base class are not inherited

Motivation for friends   

Suppose you want to compare two objects to see if they’re equal: You could use the accessor methods to carry out comparison – what’s the problem with that? You could access all of the member variables directly – what’s the potential problem with that?



Lets say we want to define an external function that could still get access to the private members of a class.

Friend  

A friend function of a class has access to the private members of that class. A friend function can directly read and change the value of a member variable.

Friend Class  

You can also have a friend class. B has access to secret.

Friend    

Friendship isn’t reciprocal. Friendship isn’t transitive. Friendship isn’t inherited. You should use members when you can and friends when you have to. o The choice is based on design, syntactic suitability, and when its much harder to do it the other way.

Overloading  

Overloading lets us reuse the same name but for different situations. Functions have the same name but different parameter. o Overloading functions can make programs clearer and more readable. o Based on different return types? No. Overloaded functions must have different parameter lists.

Friends and operators 

If we overload an operator, we want to mimic the existing operator behaviour, but using one of our classes.

LECTURE 7 | 12TH AUGUST Inheritance: redefining vs overloading, Polymorphism Multiple inheritance  

When something inherits behaviour from two (or more) different objects! Deriving directly from more than one class is called multiple inheritance

   

How does this look like? What are possible problems? The child gets all of the parents’ behaviours. The order of derivation matters only for the order of default initialisation and cleanup by constructors and destructors. What happens if you derive from one class more than once? I mean directly!



Example



But we have ambiguity. Why? o We have to refer to Bird::Animal or SeaC::Animal o This is called a qualified class name.

Using virtual  

Referring to the same base class through different inheritance pathways is ambiguous if we are referring to two different versions of the base class. Using virtual in the declaration of inheritance means that the grandchild inherit only one sub object of the base class.

Example

 

We no longer have ambiguity because all references to Animal in Penguin go to the same class. Look carefully at where we use virtual to control this.

Multiple Inheritance  

Its possible to mix up the use of virtual and have some derived classes sharing a base class and some not. Always make sure you understand why you are using a keyword!

Ambiguity on defined names  

Names must be unique in their space. You can declare namespaces to provide a scope for variables

Polymorphism 



The interface to types. We need to meanings name.

Compile-time  



How is it we need? Here, the C+ which before the running. (note that it checking). There’s time

provision of a single entities of different associate multiple with one function checking compiled? What do + compiler decides function to call program starts This is redefinition uses compile-time another way: runchecking.

Run-time checking   

C++ uses a mechanism called late binding or dynamic binding to determine which version of a function it calls at any particular time. This happens when the code is being executed and the system can determine which function to call, based on the subclass that is being used. This allows us to really use polymorphism.

The virtual keyword and the process    

Declare the function in the parent class with keyword “virtual” – virtual int test (int n, int acc); C++ makes a virtual table for that class. The table is copied for a child class, and the addresses are overridden, as the functions are re-implemented in child. At compile time. Wh...


Similar Free PDFs