280 likes | 429 Views
CS225: Data Structures and Software Principles Lectures 2, 3, and 4. An Introduction to C++. TA Info. Name: Andra Ivan Sections: 1-3 M, 3-5 T Office Hours: 10 – 12 T Email: cs225ta4@cs.uiuc.edu Office: 0212 Siebel. Outline. Motivation Declarations Classes in C++ File Organization
E N D
CS225: Data Structures and Software PrinciplesLectures 2, 3, and 4 An Introduction to C++
TA Info • Name: Andra Ivan • Sections: 1-3 M, 3-5 T • Office Hours: 10 – 12 T • Email: cs225ta4@cs.uiuc.edu • Office: 0212 Siebel
Outline • Motivation • Declarations • Classes in C++ • File Organization • Preprocessor directives • I/O in C++ • Pointers in C++ • Memory operations • Arrays and Strings in C++ • Pointer Arithmetic • Code Review
Motivation • Why C++ • Mainly superset of C • Efficient & powerful • Object Oriented (OOP) • Why Data Structures • Choosing the appropriate data structures is key to efficiency of your code • Know data structures, don’t re-invent the wheel • Some future courses rely on this material
Java vs. C++ Similarities • Language primitives • Control statements • Expressions, operators and statement syntax Differences • I/O facilities • Global variables • Libraries • Inheritance (differs appreciably) • Exception handling* • Pointers • Explicit de-allocation of memory • Templates
Declarations • Declaring variables of built-in types • int n; (C++ and Java) • Declaring variables of user-defined types • Coord c1; (C++ only) In Java, instance is not created unless new is used. • Allocating objects of built-in types • int* nPtr = new int; (C++ only) • Allocating objects of user-defined types • Coord* cPtr = new Coord(); (C++) • Coord mycoord = new Coord(); (Java)
Classes in C++ Similar to those in Java except that • there is a semi-colon at the end of the declaration • there is grouping of variable access permissions • classes need not be themselves named public,private,etc. • there is file organization (convention) • header files need not have the same name as the class
File Organization • main() function usually in a separate file (driver) • .h file • class declaration and function headers • #ifndef … #endif * • Remember preprocessor directives • .cpp or .cc or .C file • #include • class implementation • remember scope resolution operator: class::classMethod()
Preprocessor directives • #define #define PI 3.1418 #define AREA(radius) PI*(radius)*(radius) • #include • library files (#include <file1.h>) • local files (#include “file2.h”) Need to give the full path • #if, #else, #elif , #endif • #ifdef, #ifndef, #endif • Common convention is to use all capitals • No semi-colon at the end of a directive • Example: When we want to ensure that COORD_H is defined only once #ifndef COORD_H #define COORD_H // class definition #endif
I/O in C++ • You have to include the standard library #include <iostream.h> • cin standard input stream cin >> num; • cout standard output stream cout << “The value of num is :“<<num<<endl;
Pointers in C++ • Concept of pointers absent in Java • A pointer is a variable which holds a memory address. Usually represented in hex format. & -- address of * -- dereference (what is the object being pointed to?) • You will also encounter the unary operator & (address-of) and the binary operator -> while dereferencing members of structures.
Pointer Example # include <iostream.h> int main() { int* ptr; // Pointer to an integer int a; // Just a normal integer a = 5; // Store the value 5 in a ptr = &a; // Store’s a’s address in ptr cout << endl << endl; cout << “&a = “ << &a << endl; cout << “ptr = “ << ptr << endl << endl; cout << “a = “ << a << endl; cout << “*ptr = “ << *ptr << endl << endl; cout << “&ptr =“ << &ptr << endl << endl; return 0; }
Sample Code date.h #ifndef DATE_H #define DATE_H class Date { private: int month; int day; int year; public: void SetDate(int currMonth, int currDay, int currYear); void Print(); }; #endif
Sample Code date.C #include “date.h” #include <iostream.h> void Date::SetDate(int currMonth,int currDay,int currYear) { month=currMonth; day=currDay; year=currYear; } void Date::Print() { cout<<“The date is:”<<month<<“/”<<day<<“/”<<year<<endl; }
Sample Code main.C #include “date.h” int main() {Date d; d.SetDate(8,28,2001); d.Print(); return 0; }
Pointers and Classes Use of -> operator (‘-’ followed by a ‘>’) #include “date.h” void main() { Date* dPtr = new Date(); dPtr->SetDate(9, 1, 2000); //same as (*dPtr).SetDate(9,1,2000); dPtr->Print(); //same as (*dPtr).Print(); delete dPtr; }
Memory Operations • Heap and Stack Memory • The new operator • The delete operator • Concept of NULL • Pitfalls • Dangling references • Memory leaks • Every new should match a delete and every new[] should match a delete[]
Dangling Pointer – How and Why int *myPointer = new int(); *myPointer = 10; cout << "The content of myPointer is " << *myPointer << endl;delete myPointer; /* Note that even after delete, myPointer points to a valid address. But that address/memory location might be assigned to some other process (for example – another user program.) If that process modifies that memory, the cout below is going to give an unexpected value. That is a bug - dangling reference*/ cout << "The value of myPointer is " << *myPointer << endl; • Solution : use NULL
Memory Leak – Example If a function or piece of code allocates memory for its use and does not deallocate before exiting, that memory is never going to be reallocated, because the operating system/ compiler never comes to know that the memory is no longer in use. (Note: In Java, there is automatic garbage collection, which takes care of this.) Example: void f() { int a[] = new int[1000]; for (int I=0; I<100000; I++) { /* do_something */ } //delete a[]; }
Arrays and Strings in C++ • C++ arrays • Local – fixed size int array[5]; • Dynamic int* array = new int[5]; int* dynam = new int[user_input]; • Strings in C++ • null terminated char string[] = “Data Structures”;
Pointer Arithmetic • Arrays are stored in contiguous memory • someArry[i] <==> *(someArry + i) • Example:int iArry[4]; iArry[2] = 20; cout << “Element 3 is “ << *(iArry+2) << endl; output: Element 3 is 20
Code Review • Important aspect from the Software Engineering perspective • More efficient than testing • Problems and not symptoms are detected by reviews unlike in testing • In testing the presence and not the absence of errors is revealed
Syntax Errors? What will be of immediate use for us? CHECKLIST • “;” after class • =s= or = • arrays indexed correctly • loops iterate correct # of times? • include all needed files • variable spelling • delete dynamic data
About the makefile • A "makefile" is typically a list of rules and dependencies with corresponding commands to create "targets" using the rules and dependencies specified • Typing make at the command line will build and run your project • make -f MyMakefile selects the makefile of choice
How to… • The makefile is composed of: target: dependencies [tab] system command • Example: project.exe : main.obj io.obj • A macro definition line is a makefile line with a macro name, an equals sign “=”, and a macro value. In the makefile, expressions of the form $(name) or ${name} are replaced with value
Excerpt from makefile $(EXENAME): $(OBJS) $(LINK) $(LINKOPTS) $(OBJS) clean: -rm *.o $(EXENAME) -rm -rf SunWS_cache asserts.o : asserts.h asserts.cpp $(CC) -c $(CCOPTS) asserts.cpp list225.o : list225.h list225.cpp asserts.h $(CC) -c $(CCOPTS) list225.cpp string.o : string.h string.cpp asserts.h $(CC) -c $(CCOPTS) string.cpp listTestUtil.o : listTestUtil.h listTestUtil.cpp list225.h string.h $(CC) -c $(CCOPTS) listTestUtil.cpp main.o : main.cpp asserts.h list225.h string.h listTestUtil.h $(CC) -c $(CCOPTS) main.cpp
Summary • C++ and Java • Declarations and Classes • File Organization and the convention • Preprocessor • I/O • Pointers, pointer arithmetic • Arrays and Strings • Code Review
Misc • Course website • Newsgroups • Course website: Resources -> Outside Links -> accessing newsgroups with Pine from EWS • class.cs225 and class.cs225.announce • nntp server name news.cs.uiuc.edu/user=USERNAME • EWS account