1 / 41

Chapter 1 Introduction to C++:

Chapter 1 Introduction to C++:. Name space: Defines an area in which names have scope. Can use the same name in different name spaces. Header file (file with a .h extension)

moses
Download Presentation

Chapter 1 Introduction to C++:

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. Chapter 1 Introduction to C++: • Name space: • Defines an area in which names have scope. Can use the same name in different name spaces. • Header file (file with a .h extension) • files included in the compilation of a program. Usually contain types, definitions and declarations, but not executable code. • Source file (file with a .cpp extension) • contains source code to be compiled.

  2. Always back up source and header files (frequently)!!! • Demo01. • Note that compiling a program creates very large files. • Also demo02 • shows how a gui can be set up. This will NOT be a focal point of the class.

  3. Chapter 2 Numbers and objects: • Data types • float, int (32-bit in VC++ .NET), double (64-bit float) • Operators • +, -, *, /, ++, --, %, etc. • NOTE: Do not use % with negative integers; it’s different from the strict mathematic definition of % (modulus).

  4. Most of this is similar to Java. • More on cin, cout. • can input multiple nos with one cin but it’s not recommended. • String input – does not read spaces. • int input – make sure NOT to input a float number. The fractional part is ignored and remains in the buffer. • endl is a newline for output streams.

  5. static casting – see page 49-50. • const qualifier for variables. Always use in place of actual numbers. • DO NOT USE magic numbers(p. 53). • enumerated types • Similar to constant ints in java. • See book example page 54.

  6. Math functions • Need: #include <cmath> for Visual studio. • Might be #include <math.h> in other environments. • See page 58 for math functions. • string types. • Need #include <string> • Demos have examples. • See also p. 62-63.

  7. Always initialize variables. • Use meaningful variable names. • Use // for short comments. Use /* and */ pair for lengthy or frequently changing comments. • Always use a readable code layout. • Indent, format, use visual separators, align (code and output). • See demos

  8. Chapter 5 Designing and writing a class: • A class has two parts • Interface(in a header file) and • implementation(in a cpp file). • Chapter 5 does not show this initially, but it should be done!

  9. Interface: • Variable definitions, constructors, and method signatures. • How the user interacts with the class. • Implementation: • Code for the methods.

  10. Method types: • Every method identified in the interface must be defined in the implementation. • See chapter 5 and demos for syntax. • Mutator: • method that changes the object state. • Accessor: • method that is not a Mutator. Should have a constqualifier (p. 239). • See potential problem on p. 240.

  11. Constructors • Default constructor has no parameters. • Examples on page 241. Or Build your own constructors with parameters (p. 244). • You should always write a default constructor!! They are used if a class variable is declared. • Example, the following will NOT compile:

  12. #include <iostream> using namespace std; class Test { public: Test (int value); intgetdata() { return data; } private: int data; }; Test::Test(int value) { data = value; } int main() { Test x; Test y(5); cout << x.getdata() << endl; cin.get(); return 0; }

  13. There are two possible solutions: • Write a second constructor, Test::Test() and set data to a default value • Modify the above by writing Test::Test(int value = 0)

  14. NOTE: prose on page 241. • MUST initialize numeric data fields. • A string would automatically be instantiated as an empty string. • If the previous example also contained a string variable, it would NOT need to be specified in the parameter list.

  15. When two methods have the same name but different parameter sets, the function name is overloaded.

  16. Caution:Consider the example void funtest(inti, double d) { cout << "\n\nfuntest(inti, double d) called."; cout << "\nPar1 i = " << i << " ; Par2 d = " << d << endl; } void funtest(double d, inti) { cout << "\n\nfuntest(double d, inti) called."; cout << "\nPar1 d = " << d << " ; Par2 i = " << i << endl; }

  17. Include the following in main. Show what happens when comments are removed. Why? funtest(1.2, 5); funtest(3,5.5); //funtest(4, 5);

  18. Destructors. • Called when object goes out of scope. • Different from Java - you will need to write destructors. • Get in the habit of doing so now.

  19. Same issues with private/public (encapsulation) as you saw in the Java courses. • implicitand explicit parameters: • an explicit parameter is identified in the method name. • An implicit parameter is the object specified when the method was called.

  20. Accessors should always have a const qualifier. • Recall the example on page 240. • DO NOT call a constructor for an object a second time. • i.e. do not explicitly invoke a constructor on an existing object. • CAN call constructors of other classes from a constructor (page 247-8). • Elaborate on Advance Topic 5.1 (p. 247) and note the field initializer list.

  21. Design the Investment class of Demo03. • Section 5.8 discusses non-member functions, functions that are not members of any class. I will periodically use for illustrative purposes and sometimes in test harnesses. However, when using OOD, it’s best to NOT use them. • Section 5.9 discusses header files.

  22. Book Notes • Watch for missing and extraneous semicolons. Sometimes the compiler generates a message several lines beyond where it occurred. • Do not mix >> and getline input commands. • Do not mix << and printf output commands. • See the random fact on p. 243.

  23. Chapter 17 Exception Handling: • Exception: • loose definition – a situation for which normal activities cannot proceed. • Can be caused by: bad data, incorrect inputs, non-existent files, impossible tasks (divide by 0, square root of a negative number), etc. • Issues: • Who must deal with them and how?

  24. Book example • Stack class with methods: push, top, pop, and size. Designed by programmer P1 • Application that uses stack designed by programmer P2. • What if there is an attempt to pop an empty stack and the application aborts?

  25. P1 provides the ability to check for it and argues P2 used the stack improperly. • P2 argues P1 should have anticipated such problems. • Stack class would be more reliable and robust if there were a better error checking mechanism. • Programmers should not make assumptions regarding the user -- probably should also not make assumptions about other programmers who use their code.

  26. See quality Tip p. 669. • Some traditional ways to deal with errors: • Printing error messages in certain conditions. • Limited use: not always useful in production runs where there is no user watching the screen or real-time software where a user interaction takes too long. • What if the user does not understand the language in which the message is printed?

  27. Common example • method to calculate a square root displays a message if the incoming parameter is negative. This is a bad design. • flight controller error handler message • “incoming plane altitude too low – press enter to continue”

  28. Using functions to return error codes. Of course, application must still check it. Also function may already be designed to return something (an object, for instance). • See common error p. 671. • External flags: See examples on page 672.

  29. What if you had y = sqrt(atoi(x)) where x is a string. Each of atoi and sqrtcan generate a different errno? Another reason why global variables are not good. • assert command. • Causes program to halt under certain conditions. This is not always desirable. See p. 673.

  30. Error handler functions • Uses a pointer to a function to handle errors when they occur. • See p. 673 and code snippet from the next slide.

  31. #include <iostream> using namespace std; int eh1() { cout << "input is a negative number" << endl; return 1; } int eh2() { cout << "input is 0" << endl; return 2; } int (*test())() { float x; cin >> x; if (x==0) { return eh2; } if (x<0) { return eh1; } } int main() { int (*f) (); f = test(); (*f) (); cin.get(); return 0; }

  32. Exception handling is the more accepted way of dealing with problems. • Similar to Java exceptions. General form: try { code } catch (type1 e1) { code } catch (type2 e2) { code } : : catch (typen en) { code } • Somewhere in the try (or in methods called from the try there must be a throw exception command.

  33. Example try/catch code below. logic_error(“string”) is a standard exception class declared in <stdexcept>. float x; cin >> x; try { if ( x < 0 ) throw logic_error("negative value"); } catch (logic_error& e) { cout << "Error: " << e.what() << endl; cin.get(); exit (0); } cout << sqrt(x) << endl; //don’t forget #include <cmath> cin.get(); return 0;

  34. Can throw and catch anything, but special error classes are typical • Might look at example on p. 677, but don’t do this! • Look at demo03 investment program with exceptions built into it. • Note: two different types of exceptions (invalid numeric data and invalid characters in the input). Note also the locations of the throw instructions.

  35. Can build derived exception classes from base exception classes. • See standard exception hierarchy on p. 678. • Demo03 has an alternative definition for the AppError class that is a derived class. • Can change comments to use or remove it. • Why do this? See p. 678.

  36. Can use a catch clause using three dots (catch(…)) to mean “all remaining exceptions”. • Note common error p. 682. • If an exception is thrown AFTER dynamically creating memory the handler MUST remember to free it. Or else you have memory leaks!! This will be relevant later in this course!!

  37. Can specify in method declaration exactly what exceptions a method can actually throw. See syntax on p. 686-7. • Improper exception handling caused an ESA (European Space Agency) rocket to explode in 1996. • See the quality tips and random facts on p. 687-8.

  38. Where to catch and throw exceptions: • Example (sqrt method) Double sqrt(double x) { Try { if (x < 0) Throw exception } Catch exception { Some logic }

  39. What is wrong with this? • Sqrt method is written to be used by others • Coder of sqrt is deciding what to do when exception is thrown. • In effect the coder is speaking for those who want to use the method.

  40. Application may be calling sqrt • for a value input from a keyboard. In that case may want to re-input. • for a value input from a file. In that case, may want to skip data. • for a value generated elsewhere. In that case, may want to perform alternative logic.

  41. Rule of thumb: • Throw exception at the deepest level of program code as possible – at the very last possible place where the error must be checked • Catch the exception at the highest level possible – closest to the application that uses the code. • Let’s the user of the service decide what to do when errors occur.

More Related