1 / 107

CSCE 3110 Data Structures & Algorithms

CSCE 3110 Data Structures & Algorithms . C++ warm-up. History and overview Basic features Parameter passing Classes Inheritance and virtual Header file IO Memory Management Big three: destructor, copy constructor, and assignment operator Const Template. History of C++.

chesna
Télécharger la présentation

CSCE 3110 Data Structures & Algorithms

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

E N D

Presentation Transcript


  1. CSCE 3110Data Structures &Algorithms C++ warm-up

  2. History and overview • Basic features • Parameter passing • Classes • Inheritance and virtual • Header file • IO • Memory Management • Big three: destructor, copy constructor, and assignment operator • Const • Template

  3. History of C++ • 1972: C language developed at Bell Labs • Dennis Ritchie wrote C for Unix OS • Needed C for work with Unix • late 70s: C becomes popular for OS development by many vendors • Many variants of the language developed • ANSI standard C in 1987-89

  4. History of C++ (continued) • early 80s: Bjarne Stroustrup adds OO features to C creating C++ • 90s: continued evolution of the language and its applications • preferred language for OS and low level programming • popular language for application development • low level control and high level power

  5. Conceptually what is C++ • Alternatives: • is it C, with lots more options and features? • is it an OO programming language with C as its core? • is it a development environment? • On most systems it is a development environment, language, and library, used for both procedural and object oriented programming, that can be customized and extended as desired

  6. Versions of C++ • ANSI C++ • Microsoft C++ (MS Visual C++ 6.0) • Other vendors: Borland, Symantec, Turbo, … • Many older versions (almost annual) including different version of C too • Many vendor specific versions • Many platform specific versions • For this class: Unix / Linux based versions • g++

  7. Characteristics of C++ as a Computer Language • Procedural • Object Oriented • Extensible • ...

  8. Other OO Languages • Smalltalk • pure OO language developed at PARC • Java • built on C/C++ • objects and data types • Eifel and others

  9. What you can do with C++ • Apps (standalone, Web apps, components) • Active desktop (Dynamic HTML, incl Web) • Create graphical apps • Data access (e-mail, files, ODBC) • Integrate components w/ other languages

  10. Disadvantages of C++ • Tends to be one of the less portable languages • Complicated? • 40 operators, intricate precedence, pointers, etc. • can control everything • many exceptions and special cases • tremendous libraries both standard, vendor specific, and available for purchase, but all are intricate • Aspects above can result in high maintenance costs

  11. Advantages of C++ • Available on most machines • Can get good performance • Can get small size • Can manage memory effectively • Can control everything • Good supply of programmers • Suitable for almost any type of program (from systems programs to applications)

  12. History and overview • Basic features • Parameter passing • Classes • Inheritance and virtual • Header file • IO • Memory Management • Big three: destructore, copy constructor, and assignment operator • Const • Template

  13. Primitive Types • bool true or false (only C++) • char 8/16-bit • short 16-bit signed integer • int 32-bit signed integer • unsigned 32-bit unsigned integer • long 32 / 64-bit signed integer • float 32-bit floating point • double 64-bit floating point

  14. Operators and Precedence • [] . • to access arrays elements / to access object methods and fields • expr++ expr-- ++expr --expr ! • new (type)expr • * / % • + - • << >> (integers only) • < > >= <= • == != • &

  15. Operators and Precedence • ^ • | • && (booleans only) • || (booleans only) • ?: • = += -= *= …. • C++ allows operator overloading

  16. Precedence Example • What is: 5 + 21 / 4 % 3 • = 5 + (21 / 4) % 3 • = 5 + ( 5 % 3) • = 5 + 2 • = 7

  17. Explicit Casting • (type) expression • Possible among all integer and float types • Possible among some class references • E.g. int i = (int) ( (double)5 / (double)3 )

  18. Implicit Casting • Applied automatically provided there is no loss of precision • float  double • int  double • Example • int iresult, i=3; • double dresult, d=3.2; • dresult = i/d => implicit casting dresult=0.9375 • iresult = i/d => error! Why? Loss in precision, needs explicit casting

  19. Control Flow if (boolean) statement; else if(boolean) statement2; else statement3; Booleans only, not integers! • if (i > 0)  correct • if (i = 2)  correct / incorrect ?

  20. Switch / case • switch (controlVar) { case 'a' : statement-1 break; case 'b' : statement-2 break; default : statement-3 break; } • Do not forget the break command to avoid surprise result!

  21. Loops while(<boolean>) statement; do statement; while(<boolean>) for(init-expr; <boolean>; incr-expr) statement;

  22. Loop Refresher • Which loops must execute their statements at least once? • Which loops can choose to never execute their statements? • Which value of the boolean indicates to do the statements again?

  23. Some Conventions for Variable Names • Use letters and numbers • Do not use special characters including spaces, dots, underlines, pound signs, etc. • The first letter will be lower case • Use variable names that are meaningful (except for occasional counters that we might call i, j, x, etc.) • You can concatenate words, and capitalize each after the first, e.g., bankBal, thisAcctNum, totAmt • If you abbreviate, be consistent. For example do not use both bankBal and totalBalance as variable names.

  24. Some Conventions for Struct and Class Names • In creating names of structs and classes, apply the same rules as for variable names, except the first character will be upper case • Example: • an object's name: myCar • the struct or class name: Car • Another Example: aPerson and Person

  25. Overview • History and overview • Basic features • Parameter passing • Classes • Inheritance and virtual • Header file • IO • Memory Management • Big three: destructore, copy constructor, and assignment operator • Const • Template

  26. Passing Parameters • C++ allows for three different ways of passing parameters: • Pass “by value” • E.g. foo (int n) • Appropriate for small objects (usually primitive types) that should not be altered by the function call • Pass “by constant reference” • E.g. foo(const T& myT) • Appropriate for large objects that should not be altered by the function call • Pass “by reference” • E.g. foo(bool & errFlag) • Appropriate for small objects that can be altered by the function call • Array types are always passed “by reference”

  27. Passing by value void square(int i) { i = i*i; } int main() { int i = 5; square(i); cout << i << endl; }

  28. Passing by reference void square(int& i) { i = i*i; } int main() { int i = 5; square(i); cout << i << endl; }

  29. Passing by constant reference void square(const int& i) { i = i*i; } int main() { int i = 5; square(i); cout << i << endl; } Wont work, why?

  30. Passing by constant reference int square(const int& i) { return i*i; } int main() { int i = 5; cout << square(i) << endl; } Will t his work?

  31. What is a reference? An alias – another name for an object. int x = 5; int &y = x; // y is a // reference to x y = 10; What happened to x? What happened to y? – y is x.

  32. Why are they useful? When passing argument of large size (class type), can save space Sometimes need to change a value of an argument Can be used to return more than one value (pass multiple parameters by reference)

  33. How are references different from Pointers?

  34. Outline • History and overview • Basic features • Parameter passing • Classes • Inheritance and virtual • Header file • IO • Memory Management • Big three: destructore, copy constructor, and assignment operator • Const • Template

  35. Classes • Provide a mechanism for defining classes of objects. • We can define the class of all computers to have certain characteristics. • An instance of a computer is your home PC. • Classes contain member variables and member functions.

  36. Classes in C++:Why Create Classes / Objects? • Keeps all related info (i.e., data) together • Refer to all the related info by one name • Protect the information • Hide methods that use or change the info • Keep methods together with their related info

  37. Example of Benefits of Creating an Object • Keeps all related info (i.e., data) together Person thisPerson; Person thisPerson = new Person ("Bill", "Clinton", 52); • Refer to all the related info by one name thisPerson • Protect the information lastName = "Dole";//normally data members are private, and member functions are public

  38. Classes and Objects class Mammals inherits inherits Humans class Tigers class instance-of instance-of Hank Peggy Tony

  39. Example of a Simple Class class Change { private: int quarters; int dimes; public: int getQuarters() {return quarters;} int getDimes() {return dimes;} void setQuarters(int aQuarters) {quarters = aQuarters;} …... void printChange() {cout << "\nQuarters: " << quarters << " Dimes: " << dimes << endl; } };

  40. More Class Example class human { // this data is private to instances of the class int height; char name[]; int weight; public: void setHeight(int heightValue); int getHeight(); };

  41. Function Definitions void human::setHeight(int heightValue) { if (heightValue > 0) height = heightValue; else height = 0; } int human::getHeight() { return(height); }

  42. Example Output // first we define the variables. int height = 72; int result = 0; human hank; //set our human’s height hank.setHeight(height); //get his height result = hank.getHeight(); cout << “Hank is = “ << result << “inches tall” << endl; Hank is 72 inches tall

  43. Instantiating an Object • The class definition does not create any objects • Instantiating and constructing are equivalent words for building a new object based on the model (i.e., template) of the class • Instantiating is done just like declaring a variable of a built in data type • Instantiating is done by a constructor (sometimes called a constructor method) • If the "class provider" does not provide a constructor, then the C++ compiler provides a default one automatically • The default constructor does not provide values to the data members (i.e. the instance variables)

  44. Instantiating an Object (more) • When the object is instantiated, memory is allocated • Example of instantiation (implicit call of constructor) Car myCar; Elephant oneElephant, twoElephant; • No initialization takes place • Each object has its own memory allocation • oneElephant and twoElephant are separate objects in different locations in memory • Each is addressed individually by name or location • Each data member is addressed individually using the object name and the data member name, for example: oneElephant.age twoElephant.name

  45. Referencing an Object • Each object has a name (or a location) which is assigned when the object is instantiated • private data members are accessible only within the class • since most data members are private, that means that these data items are accessed generally by means of member functions • myElephant.age = 72; //won't work, assuming age //is declared as private • myElephant.setAge(72); // will work

  46. Outline • History and overview • Basic features • Parameter passing • Classes • Inheritance and virtual • Header file • IO • Memory Management • Big three: destructore, copy constructor, and assignment operator • Const • Template

  47. Inheritance • The power of object-oriented languages • Enables reuse of fields/methods • All parent fields included in child instantiation • Protected and public fields and methods directly accessible to child • Parent methods may be overridden • New fields and methods may be added to the child • Multiple inheritance

  48. Inheritance (cont’d) class classname: public parentname { private: ….; public: ….; //access to parent methods through // parentname::methodname … }

  49. Outline • History and overview • Basic features • Parameter passing • Classes • Inheritance and virtual • Header file • IO • Memory Management • Big three: destructore, copy constructor, and assignment operator • Const • Template

  50. Header file • For complex classes, the member functions are declared in a header file and the member functions are implemented in a separate file. • This allows people to look at the class definitions, and their member functions separately • The header file needs to be included in your program when you use the classes defined in the head file

More Related